Created
February 5, 2021 13:22
-
-
Save bishil06/6c3a060b33f551ee9acc03188f964dcc to your computer and use it in GitHub Desktop.
Node.JS create md5 hash from file
This file contains hidden or 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 crypto = require('crypto'); | |
function createMD5(filePath) { | |
return new Promise((res, rej) => { | |
const hash = crypto.createHash('md5'); | |
const rStream = fs.createReadStream(filePath); | |
rStream.on('data', (data) => { | |
hash.update(data); | |
}); | |
rStream.on('end', () => { | |
res(hash.digest('hex')); | |
}); | |
}) | |
} |
data += chunk
the "improved" version fails on big files (bigger than RAM)
it wont get better than the original post
similar solutions:
https://stackoverflow.com/a/44643479/10440128
https://gist.github.com/F1LT3R/2e4347a6609c3d0105afce68cd101561
https://dev.to/saranshk/how-to-get-the-hash-of-a-file-in-nodejs-1bdk
one more!
import { createReadStream } from 'node:fs'
import crypto from 'crypto'
function md5sum(path) {
// const md5 = await md5sum(path)
// https://stackoverflow.com/a/44643479/10440128
return new Promise((resolve, reject) => {
const hash = crypto.createHash('md5')
const stream = createReadStream(path)
stream.on('error', err => reject(err))
stream.on('data', chunk => hash.update(chunk))
stream.on('end', () => resolve(hash.digest('hex')))
})
}
async function main() {
const path = process.argv[2]
const md5 = await md5sum(path)
console.log(md5, path)
}
main()
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Improved version.