Files
factorio-clusterio/packages/lib/src/hash.ts
T
Hornwitser 2e48b728dd Remove fs-extra and klaw (#882)
These packages are obsoleted by the promises API to the built-in Node fs
module.  The fs-extra package is also causing problems with broken APIs
that don't behave the same as Node's fs module, and throwing errors
without code properties on them.
2026-04-09 22:53:13 +02:00

41 lines
974 B
TypeScript

/**
* Hashing functions
* @module lib/hash
*/
import crypto from "crypto";
import fs from "node:fs/promises";
/**
* Returns a promise that resolves to the SHA1 hash of the stream given
*
* @param stream - Node stream of the content to hash.
* @returns hash of the stream.
*/
export function hashStream(stream: NodeJS.ReadableStream): Promise<string> {
return new Promise((resolve, reject) => {
let hasher = crypto.createHash("sha1");
hasher.setEncoding("hex");
hasher.on("finish", () => {
resolve(hasher.read());
});
stream.on("error", (error) => {
// the docs doesn't say anything about what's passed on error
reject(error);
});
stream.pipe(hasher);
});
}
/**
* Returns a promise that resolves to the SHA1 hash of the file given by path
*
* @param path - Path to the file to hash.
* @returns hash of the file given.
*/
export async function hashFile(path: string) {
return hashStream((await fs.open(path)).createReadStream());
}