Hashing a file using node.js

Create md5 hash of a file using streams and crypto module of node.js



Overview

In the snippet, we will hash new.txt file using node.js streams and crypto module.

  • Create a read stream to read the contents of the the file.
  • Store the contents of the file in a variable.
  • Call the getHash() function which is used to calculate the md5 hash of the contents of the file.

Code


													
//Name of the File : generating-hash-of-file.js
var fs = require('fs');
var crypto = require('crypto');
var getHash = ( content ) => {				
				var hash = crypto.createHash('md5');
				//passing the data to be hashed
				data = hash.update(content, 'utf-8');
				//Creating the hash in the required format
				gen_hash= data.digest('hex');
				return gen_hash;
}
//Creating a readstream to read the file
var myReadStream = fs.createReadStream('new.txt');

var rContents = '' // to hold the read contents;
myReadStream.on('data', function(chunk) {
		rContents += chunk;
});
myReadStream.on('error', function(err){
		console.log(err);
});
myReadStream.on('end',function(){
		//Calling the getHash() function to get the hash
		var content = getHash(rContents) ;
		console.log('Content : ' + rContents);
		console.log('Hash : ' + content);
});
													
												

Run

  • Now run the snippet using the following command :
    													
    >node generating-hash-of-file.js
    Content : Lorem ipsum dolor sit amet, eu scripta molestie democritum usu, sed probo ocurreret no.
    Id augue equidem ius. Eum eu feugiat urbanitas. Vim accusam patrioque id, quo id essent
    feugiat fuisset, ea tollit probatus elaboraret est. In his modo clita tamquam, no ius
    conceptam vituperatoribus. Tale laudem percipit usu cu, nihil detraxit iudicabit ad his.
    Eum in dicit fastidii mandamus.
    
    Hash : 3c7f2a35e23a26d7a6b755f5a55cf56b
    													
    												

Summary

We have created the hash of a file using crypto module of node.js and streams module of node.js