createHash Digests Data Incrementally
Feed chunks into createHash with repeated update calls and compare the digest against a one-shot hash to prove hashing is incremental.
Code
import { createHash } from 'node:crypto';
const payload = 'block-1:block-2:block-3:block-4';
// one-shot digest of the whole payload
const whole = createHash('sha256').update(payload).digest('hex');
// incremental updates produce the same digest: hashing is streaming-friendly
const chunked = createHash('sha256');
const parts = payload.split(':');
for (let i = 0; i < parts.length; i++) {
if (i > 0) chunked.update(':');
chunked.update(parts[i]);
}
const incremental = chunked.digest('hex');
console.log('digests identical:', whole === incremental);
console.log('digest length:', incremental.length);
console.log('digest prefix:', incremental.slice(0, 16));Output
Captured from a sandboxed run of this snippet in the build pipeline.
digests identical: true
digest length: 64
digest prefix: c51ed856153984b8How the snippet works
Iteration happens inside for (let i = 0; i < parts.length; i++) — everything outside it runs once. The only import source is node:crypto, a Node.js built-in, exposing createHash.
Module-level bindings hold the data — payload, whole, chunked, parts — with no function scope in between.
Caveats
node:cryptoresolves inside Node.js without any package — it is a core module.cryptoexist only in browsers — a Node runtime has no shims for them out of the box.
Applying it
Running the file prints labeled results such as digests identical:, digest length:, digest prefix: — each operation’s effect is visible in the output.
Statements that matter
const whole = createHash('sha256').update(payload).digest('hex');
const payload = 'block-1:block-2:block-3:block-4';
const incremental = chunked.digest('hex');
Interactive Tools for This Topic
SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.HMAC GeneratorCompute an HMAC-SHA-256, SHA-384, or SHA-512 signature for a message and key using the Web Crypto API, with hex and Base64 output.Webhook HMAC Signature VerifierVerify and generate HMAC-SHA256 webhook signatures for Stripe, GitHub, and raw hex headers locally using Web Crypto and constant-time comparison.
FAQ
- Are there third-party dependencies?
- No. The imports resolve to Node.js core modules, which the runtime provides.
Report a problem with this exampleOpens a pre-filled issue on GitHub.