Files
factorio-clusterio/packages/lib/hash.js
T
Hornwitser 921ebad8fb Allow importing libHash to succeed in browser
Alsthough this does not make libHash work in the browser it allows other
modules to require libHash while still being exported to the browser.
2022-08-24 15:42:26 +02:00

47 lines
1008 B
JavaScript

/**
* Hashing functions
* @module lib/hash
*/
"use strict";
const crypto = require("crypto");
const fs = require("fs-extra");
/**
* Returns a promise that resolves to the SHA1 hash of the stream given
*
* @param {Stream} stream - Node stream of the content to hash.
* @returns {Promise<string>} hash of the stream.
*/
function hashStream(stream) {
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 {string} path - Path to the file to hash.
* @returns {Promise<string>} hash of the file given.
*/
function hashFile(path) {
return hashStream(fs.createReadStream(path));
}
module.exports = {
hashStream,
hashFile,
};