Skip to content

Instantly share code, notes, and snippets.

@bestickley
Created July 31, 2023 18:19
Show Gist options
  • Save bestickley/249c878a15e5051770ce60cad83a1add to your computer and use it in GitHub Desktop.
Save bestickley/249c878a15e5051770ce60cad83a1add to your computer and use it in GitHub Desktop.
Compute Meta Hash
import { Hash, createHash } from "node:crypto";
import { readdirSync, statSync } from "node:fs";
import { join } from "node:path";
/**
* Creates hash of given files/folders.
*/
export function computeMetaHash(paths: string[], inputHash?: Hash) {
const hash = inputHash ? inputHash : createHash("sha1");
for (const path of paths) {
const statInfo = statSync(path);
if (statInfo.isDirectory()) {
const directoryEntries = readdirSync(path, { withFileTypes: true });
const fullPaths = directoryEntries.map((e) => join(path, e.name));
// recursively walk sub-folders
computeMetaHash(fullPaths, hash);
} else {
const statInfo = statSync(path);
// compute hash string name:size:mtime
const fileInfo = `${path}:${statInfo.size}:${statInfo.mtimeMs}`;
hash.update(fileInfo);
}
}
// if not being called recursively, get the digest and return it as the hash result
if (!inputHash) {
return hash.digest().toString("base64");
}
return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment