Last active
June 2, 2019 19:49
-
-
Save 2bbb/2d5cf4f6539f5211b8ecdbfaccbf83bf to your computer and use it in GitHub Desktop.
calculate hash from file stream
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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