Skip to content

Instantly share code, notes, and snippets.

@chrisvoo
Created February 19, 2019 19:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisvoo/1f10f660ce93736996e80b2288d62cb4 to your computer and use it in GitHub Desktop.
Save chrisvoo/1f10f660ce93736996e80b2288d62cb4 to your computer and use it in GitHub Desktop.
Node.js: function to create an hash from a file (path or Buffer)
const crypto = require('crypto');
const fs = require('fs');
/**
* It calculates the hash of a file
* @param {string} hashName type of hash (md5, sha1, etc)
* @param {string|Stream} file a file's path or a readable stream
* if it's been already opened somewhere else
*/
function getFileHash(hashName, file) {
return new Promise((resolve, reject) => {
const hash = crypto.createHash(hashName);
let stream;
if (typeof file === 'string') {
stream = fs.createReadStream(file);
} else if (file instanceof Readable) {
stream = file;
} else {
throw new Error('Second argument must be a string or a readable stream');
}
stream.on('error', (err) => reject(err));
stream.on('data', (chunk) => hash.update(chunk));
stream.on('end', () => resolve(hash.digest('hex')));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment