Skip to content

Instantly share code, notes, and snippets.

@TravisMullen
Last active October 20, 2019 18:55
Show Gist options
  • Save TravisMullen/dfcd1f08887be1ed82f29276308fb82d to your computer and use it in GitHub Desktop.
Save TravisMullen/dfcd1f08887be1ed82f29276308fb82d to your computer and use it in GitHub Desktop.
Generate hash from file.
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