Node.js
Calculate a file’s SHA-256 digest incrementally
Feed a file stream into a SHA-256 hash when you need a content fingerprint without reading the complete file into a Buffer. Digest the hash only after all chunks have been processed.
Worked example
Node.js example · save as example.mjs and run node example.mjs
import * as fs from "node:fs/promises";
import {tmpdir} from "node:os";
import {join} from "node:path";
const directory = await fs.mkdtemp(join(tmpdir(), "file-guide-"));
try {
const {createReadStream} = await import("node:fs");
const {createHash} = await import("node:crypto");
const path = join(directory, "sample.txt");
await fs.writeFile(path, "abc");
const hash = createHash("sha256");
for await (const chunk of createReadStream(path)) hash.update(chunk);
console.log(hash.digest("hex"));
} finally {
await fs.rm(directory, {recursive: true, force: true});
}How it works
A cryptographic hash receives the exact bytes in order. Chunk boundaries do not change the resulting digest. This makes hashes useful for verifying a copy, checking a known download, or identifying unchanged file content.
Limits and mistakes
A matching digest only establishes agreement with the reference you trust. It does not identify who created a file. Plain fast hashes are also inappropriate for password storage; use a password-specific derivation scheme for that separate problem.
Check the result
For the three UTF-8 bytes abc, expect ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad. Adding a newline changes the input bytes and therefore the digest.
Sources
Reference documentation for the behavior used in this guide: