In this tutorial, we will walk through a simple script that generates hashes for files in a Node.js project. This is particularly useful for checking if files have been modified, as a change in the file content will result in a different hash.

What is checksum/hash?

Checksum/Hash is a cryptographic hash, is a digital fingerprint of a piece of data (e.g., a block of text) which can be used to check that you have an unaltered copy of that data.

Generating File Hashes and checksum in Node.js

To check if a file has been modified, you can compare the current hash of the file with a previously stored hash. If the hashes are different, the file has been modified. Here’s how you can do it:

  1. Generate and store the hash of the file when it’s known to be unmodified.
  2. When you want to check if the file has been modified, generate the hash of the file again and compare it with the stored hash.

Here’s the code to achieve this:

const fs = require('fs');
const crypto = require('crypto');
const sriToolbox = require('sri-toolbox');

// Function to generate hash of a file
function generateHash(file) {
    const fileContent = fs.readFileSync(file);
    const hash = crypto.createHash('sha256').update(fileContent).digest('hex');
    return hash;
}

// Generate and store the hash of the file when it's known to be unmodified
const originalHash = generateHash('path_to_your_file.js');

// Later...

// Generate the hash of the file again
const currentHash = generateHash('path_to_your_file.js');

// Compare the hashes
if (originalHash === currentHash) {
    console.log('File has not been modified');
} else {
    console.log('File has been modified');
}