@thi.ng/file-io
Version:
Assorted file I/O utils (w/ logging support) for NodeJS/Bun
25 lines (24 loc) • 765 B
JavaScript
import { createHash } from "node:crypto";
import { createReadStream } from "node:fs";
import { maskedPath } from "./mask.js";
const fileHash = async (path, logger, algo = "sha256") => {
logger?.info("reading file:", maskedPath(path));
return await streamHash(createReadStream(path), logger, algo);
};
const streamHash = async (src, logger, algo = "sha256") => {
const sum = createHash(algo);
for await (let chunk of src) sum.update(chunk);
const hash = sum.digest("hex");
logger?.info(`${algo} hash: ${hash}`);
return hash;
};
const bufferHash = (src, logger, algo = "sha256") => {
const hash = createHash(algo).update(src).digest("hex");
logger?.info(`${algo} hash: ${hash}`);
return hash;
};
export {
bufferHash,
fileHash,
streamHash
};