Skip to content
Sarj Code Standards

prefer-node-crypto-hash

Prefer the modern one-shot node:crypto hash API when streaming state is unnecessary.

Why

A createHash-update-digest chain allocates mutable streaming state for a single in-memory value; Node's built-in hash function expresses the one-shot operation directly and can use its optimized fast path.

Fix

On a supported Node runtime, consider hash(algorithm, value, encoding). Preserve the output encoding explicitly: digest() returns a Buffer, while hash defaults to hex. Keep createHash for streams or multiple updates.

Examples

Before — flagged Avoid mutable state for one value
case.ts
import { createHash } from "node:crypto";
export const digest = createHash("sha256").update("value").digest("hex");
After — preferred Use Node's one-shot hash API
case.ts
import { hash } from "node:crypto";
export const digest = hash("sha256", "value", "hex");
Before — flagged An unchanged namespace retains native provenance
case.ts
const crypto = require("node:crypto");
export const digest = crypto.createHash("sha256").update("value").digest("hex");
After — preferred A replaced member has a different contract
case.ts
const crypto = require("node:crypto");
crypto.createHash = () => ({
update() {
return this;
},
digest() {
return "custom";
},
});
export const digest = crypto.createHash("sha256").update("value").digest("hex");

References