EN
Node.js - encode text to md5
6
points
In this article, we would like to show how to calculate md5 sum for indicated text in Node.js.
Quick solution:
const crypto = require('crypto'); // built-in node module
const text = 'Some input text ...';
const result = crypto.createHash('md5').update(text).digest('hex');
console.log(result); // ac57cdeee28c017e7afd39a579dab8fd
1. Using the built-in module
Node.js has a built-in crypto module that provides md5 sum implementation.
1.1. Reusable util
This section contains a simple function that with one call calculate md5 sum for the indicated text.
const crypto = require('crypto');
const calculateMD5Sum = (text) => {
return crypto.createHash('md5').update(text).digest('hex');
};
// Usage example:
const text = 'dirask';
console.log(calculateMD5Sum(text)); // 47b3201569d2797c6e0432b71e3bb9e0
1.2. Partial calculations
This approach lets to make calculations on small data parts. It is useful when we work on big files or stream data, reducing the amount of RAM that is needed to store data.
const crypto = require('crypto');
const md5 = crypto.createHash('md5');
md5.update('d');
md5.update('ir');
md5.update('ask');
const sum = md5.digest('hex');
console.log(sum); // 47b3201569d2797c6e0432b71e3bb9e0
2. Using external md5
library
Simple steps:
1. install md5
module with the following command:
npm install md5
2. run the following source code:
const md5 = require('md5');
const text = 'dirask';
console.log(md5(data)); // 47b3201569d2797c6e0432b71e3bb9e0