Last active
October 20, 2019 18:55
-
-
Save TravisMullen/dfcd1f08887be1ed82f29276308fb82d to your computer and use it in GitHub Desktop.
Generate hash from file.
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
import { createHash } from 'crypto' | |
import { createReadStream } from 'fs' | |
/** | |
* Generate hash from file. | |
* @param {string} filename - path to file. | |
* @param {string} algorithm | |
* @returns {Promise} | |
*/ | |
export const shasum = (filename, algorithm = 'sha256') => ( | |
new Promise((resolve, reject) => { | |
if (!(filename && | |
typeof (filename) !== 'string')) { | |
reject(new Error('file not found.')) | |
} | |
const hash = createHash(algorithm) | |
const input = createReadStream(filename) | |
input.on('readable', () => { | |
// Only one element is going to be produced by the | |
// hash stream. | |
const data = input.read() | |
if (data) { | |
hash.update(data) | |
} else { | |
const result = hash.digest('hex') | |
console.log(`${result} ${filename}`) | |
resolve(result) | |
} | |
}) | |
hash.on('error', error => { | |
reject(error) | |
}) | |
}) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment