node.js hash string?


Question

I have a string that I want to hash. What's the easiest way to generate the hash in node.js?

The hash is for versioning, not security.

1
294
2/21/2018 5:50:24 PM

Accepted Answer

Take a look at crypto.createHash(algorithm)

var filename = process.argv[2];
var crypto = require('crypto');
var fs = require('fs');

var md5sum = crypto.createHash('md5');

var s = fs.ReadStream(filename);
s.on('data', function(d) {
  md5sum.update(d);
});

s.on('end', function() {
  var d = md5sum.digest('hex');
  console.log(d + '  ' + filename);
});
201
5/22/2012 3:30:49 PM

If you just want to md5 hash a simple string I found this works for me.

var crypto = require('crypto');
var name = 'braitsch';
var hash = crypto.createHash('md5').update(name).digest('hex');
console.log(hash); // 9b74c9897bac770ffc029102a200c5de

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon