Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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
You can’t perform that action at this time.