File Hash Manifest

Build a sorted SHA-256 manifest of file contents so unchanged inputs can be skipped and integrity verified.

TypescriptCli Tooling

Code

typescriptsnippet
26 lines
import { createHash } from 'node:crypto';
import { readFile, readdir } from 'node:fs/promises';
import { join } from 'node:path';

export async function hashFile(path: string): Promise<string> {
  const content = await readFile(path);
  return 'sha256:' + createHash('sha256').update(content).digest('hex');
}

export async function buildManifest(root: string): Promise<Array<{ path: string; hash: string }>> {
  const entries = await readdir(root, { withFileTypes: true });
  const files = entries.filter((e) => e.isFile()).map((e) => e.name).sort();
  const manifest: Array<{ path: string; hash: string }> = [];
  for (const name of files) {
    manifest.push({ path: name, hash: await hashFile(join(root, name)) });
  }
  return manifest;
}

export function manifestUnchanged(a: readonly { path: string; hash: string }[], b: readonly { path: string; hash: string }[]): boolean {
  if (a.length !== b.length) return false;
  return a.every((entry, i) => {
    const other = b[i];
    return other !== undefined && entry.path === other.path && entry.hash === other.hash;
  });
}

Inside the snippet

File Hash Manifest keeps everything in the functions hashFile, buildManifest and manifestUnchanged.

Iteration happens inside for (const name of files) — everything outside it runs once. Every asynchronous step is awaited, so rejections surface where the call happens. createHash, readFile, readdir, join come from node:crypto, node:fs/promises, node:path — Node.js core modules the runtime ships with.

Caveats

  • node:crypto resolves inside Node.js without any package — it is a core module.
  • Uses crypto, so it needs a browser context — it will not run as-is in Node without shims.
  • The guard a.length !== b.length short-circuits the flow with an early return when its condition holds.

Using it

The main signature reads export async function hashFile(path: string)

hashFile is what another module would consume; nothing else here is load-bearing for callers.

Key statements

const files = entries.filter((e) => e.isFile()).map((e) => e.name).sort();
return a.every((entry, i) => {
const other = b[i];
return other !== undefined && entry.path === other.path && entry.hash === other.hash;
});
return 'sha256:' + createHash('sha256').update(content).digest('hex');

Interactive Tools for This Topic

FAQ

What does this import from outside the project?
Only `node:crypto`, and that is a Node.js built-in — it comes with the runtime.