How To Get The Hash of A File In Node.js

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 boast-worthy, but given others might encounter a situation where they need a hash of a file, this might help.

We use the fs module to open up the file we want to calculate the hash for, use the createHash method on the crypto package to then pass in our file buffer from the readFileSync method, and that’s it.

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 essential to you, sha1 and base64 are the two fastest options in most cases. However, all options are pretty fast anyway.

If you are using Typescript, this code will achieve the same thing:

import \* as crypto from 'crypto';
import \* as fs from 'fs';

const fileBuffer = fs.readFileSync('myfile.js');
const hashSum = crypto.createHash('sha256');
hashSum.update(fileBuffer);

const hex = hashSum.digest('hex');

console.log(hex);