Skip to content

Instantly share code, notes, and snippets.

@bishil06
Created February 5, 2021 13:22
Show Gist options
  • Select an option

  • Save bishil06/6c3a060b33f551ee9acc03188f964dcc to your computer and use it in GitHub Desktop.

Select an option

Save bishil06/6c3a060b33f551ee9acc03188f964dcc to your computer and use it in GitHub Desktop.
Node.JS create md5 hash from file
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'));
});
})
}
@milahu
Copy link

milahu commented Jul 16, 2025

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