Whilst doing some work in a library I maintain, I needed to add in the ability to calculate the hash of an included file for an integrity check feature I was adding in. The resulting solution is simple and not really boast-worthy, but given others might encounter a situation where they need a hash of a file, this might help.
const crypto = require('crypto'); const fs = require('fs'); const fileBuffer = fs.readFileSync('myfile.js'); const hashSum = crypto.createHash('sha256'); hashSum.update(fileBuffer); const hex = hashSum.digest('hex'); console.log(hex);
For the createHash
method you can supply different supported algorithms including; md5
, sha1
and sha256
. To the digest method, you can supply hex
or base64
. If speed is important to you, sha1
and base64
are the two fastest options in most cases, however, all options are fairly fast anyway.