Current Location: Home> Latest Articles> How to Implement md5_file() Equivalent Functionality in Node.js Using the Crypto Module

How to Implement md5_file() Equivalent Functionality in Node.js Using the Crypto Module

M66 2025-06-28

In PHP, md5_file() is a very convenient function used to compute the MD5 hash value of a file. Its usage is very simple:

$hash = md5_file('path/to/file.txt');

This is very useful in scenarios such as file integrity verification and cache identifier generation. However, Node.js does not have a built-in function that is exactly equivalent to md5_file(). But we can manually implement similar functionality using Node.js's core modules crypto and fs.

Node.js Implementation Approach

The crypto module in Node.js provides powerful encryption capabilities, while the fs module allows us to read file contents as streams. By combining these two, we can read file contents and calculate its MD5 hash in real-time.

Here’s the implementation code:

const fs = require('fs'); const crypto = require('crypto');

function md5File(filePath) {
return new Promise((resolve, reject) => {
const hash = crypto.createHash('md5');
const stream = fs.createReadStream(filePath);

stream.on('data', chunk => hash.update(chunk));
stream.on('end', () => resolve(hash.digest('hex')));
stream.on('error', reject);

});
}

// Usage example
md5File('example.txt')
.then(hash => {
console.log('MD5:', hash);
})
.catch(err => {
console.error('Error reading file:', err);
});

This function returns a Promise, and once the file is successfully read and the hash processing is completed, it returns the corresponding MD5 value.

Advanced Usage: Combining with Upload Validation

Assume you have built an upload service, and you need to verify whether the file uploaded by the user remains consistent before and after uploading. You can compare the MD5 value of the file before upload with the value generated on the server:

app.post('/upload', (req, res) => { const uploadedFilePath = '/tmp/uploaded.file';

// Assume you have already saved the file to uploadedFilePath
md5File(uploadedFilePath).then(serverHash => {
const clientHash = req.body.md5;

if (serverHash === clientHash) {
  res.send('File is consistent');
} else {
  res.status(400).send('File verification failed');
}

}).catch(() => {
res.status(500).send('Internal error');
});
});

Generate MD5 Value on the Browser Side

To implement the complete functionality, you may also need to generate the MD5 value of a file on the client side before uploading it. On the browser side, you can use a library like SparkMD5 in combination with the FileReader API to compute the file’s hash value.

Summary

Although Node.js does not have a quick function like PHP’s md5_file(), it’s easy to implement similar functionality using the crypto and fs modules. By using streaming processing, we can ensure memory efficiency when handling large files, making it ideal for building high-performance file verification and processing services.