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.

JavascriptData Integrity

Code

javascriptsnippet
19 lines
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: c51ed856153984b8

How 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:crypto resolves inside Node.js without any package — it is a core module.
  • crypto exist 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

FAQ

Are there third-party dependencies?
No. The imports resolve to Node.js core modules, which the runtime provides.