Introduction to md5-file
The md5-file
package is a popular JavaScript library used to generate MD5 hashes for files. This can be useful for verifying file integrity, implementing cache strategies, and more.
In this guide, we will explore various APIs provided by the md5-file
package and illustrate their usage with descriptive code snippets. We will also build a simple Node.js application that leverages these APIs.
Installing md5-file
First, let’s install the md5-file
library using npm:
npm install md5-file
Generating MD5 Hash of a File
The most basic operation is to generate the MD5 hash of a file. Here’s how you can do it:
const md5File = require('md5-file');
md5File('path/to/file.txt', (err, hash) => {
if (err) throw err;
console.log(`MD5 hash: ${hash}`);
});
Generating MD5 Hash using Promises
The md5-file
library also supports promises. Here’s an example:
const md5File = require('md5-file');
md5File('path/to/file.txt').then(hash => {
console.log(`MD5 hash: ${hash}`);
}).catch(err => {
console.error(err);
});
Using md5-file with Async/Await
If you prefer using async/await, here’s how to generate an MD5 hash:
const md5File = require('md5-file');
async function generateHash() {
try {
const hash = await md5File('path/to/file.txt');
console.log(`MD5 hash: ${hash}`);
} catch (err) {
console.error(err);
}
}
generateHash();
Practical Application – File Integrity Checker
Let’s build a simple Node.js application that checks the integrity of files in a directory:
const fs = require('fs');
const path = require('path');
const md5File = require('md5-file');
async function checkIntegrity(directory) {
const files = fs.readdirSync(directory);
for (const file of files) {
const filePath = path.join(directory, file);
const hash = await md5File(filePath);
console.log(`File: ${file} - MD5: ${hash}`);
}
}
// Check integrity of files in the 'test-directory'
checkIntegrity('test-directory');
This example iterates through all files in a given directory, prints their MD5 hashes, and helps check if they have been tampered with.
Hash: db72603ad186cb4abafe5ef448372feb3e5dba56304945997609d8c420d9da1a