Skip to content

Instantly share code, notes, and snippets.

@2bbb
Last active June 2, 2019 19:49
Show Gist options
  • Save 2bbb/2d5cf4f6539f5211b8ecdbfaccbf83bf to your computer and use it in GitHub Desktop.
Save 2bbb/2d5cf4f6539f5211b8ecdbfaccbf83bf to your computer and use it in GitHub Desktop.
calculate hash from file stream
const fs = require('fs');
const crypto = require('crypto');
const hash_from_file = (file, algorithm = 'sha256') => new Promise((resolve, reject) => {
try {
const stat = fs.statSync(file);
const hash = crypto
.createHash(algorithm)
.setEncoding('hex');
fs
.createReadStream(file)
.pipe(hash)
.once('error', reject)
.once('finish', () => resolve(`${hash.read()}-${stat.size.toString(0x10)}`));
} catch(err) {
reject(err);
}
});
async function main() {
try {
const hash = await hash_from_file("/Users/2bit/demo.mp3", 'sha1');
console.log(hash);
} catch(err) {
console.error(err);
}
};
// main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment