How to calculate MD5 hash in node.js

First a little intro to Hashes, for those who are very new to Hashes

What is a Hash?

A hash is a fixed-length string of bits that is procedurally and deterministially generated from some arbitrary block of source data. Some important properties of these hashes (the type useful for cryptography) include:

Fixed length: This means that, no matter what the input, the length of the hash is the same. For example, md5 hashes are always 128 bits long whether the input data is a few bits or a few gigabytes.

Deterministic: For the same input, you should expect to be able to calculate exactly the same hash. This makes hashes useful for checksums.

Collision-Resistant: A collision is when the same hash is generated for two different input blocks of data. Hash algorithms are designed to be extremely unlikely to have collisions — just how unlikely is a property of the hash algorithm. The importance of this property depends on the use case.

Unidirectional: A good hash algorithm is easy to apply, but hard to undo. This means that, given a hash, there isn’t any reasonable way to find out what the original piece of data was.

Some of the most common hash types are SHA1 and MD5

Now how to calculate Hash in Node.js

Node.js have a module named Crypto, which has a method called createHash which allows you to calculate a hash. Its only argument is a string representing the hash This example finds the md5 hash for the string, “I love Node.js”

var crypto = require('crypto');
var name = 'I love Node.js';
var hash = crypto.createHash('md5').update(name).digest("hex");

The update method is used to push data to later be turned into a hash with the digest method. update can be invoked multiple times to ingest streaming data, such as buffers from a file read stream. The argument for digest represents the output format, and may either be “binary”, “hex” or “base64”. It defaults to binary.

How to use HTML with Express (Node.js)

There is no direct way of using HTML under Jade, which comes with Express by default, But if you want to use more HTML-style templates, you could use els instead of Jade. Follow these steps to use ejs instead of Jade –

1) Install ejs –

npm install ejs

2) Set your template engine in app.js as ejs

// app.js
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

3) Now in your route file you can assign template variables –

// ./routes/index.js
exports.index = function(req, res){
  res.render('index', { title: 'ejs' });

4) Then you can create your html view in /views directory.

// ./views/index.html
<h1>Welcome to <%= title %>!</h1>