const crypto = require('crypto');
const fs = require('fs');
// Function to hash a file using streams
function hashFile(filePath, algorithm) {
return new Promise((resolve, reject) => {
// Create hash object
const hash = crypto.createHash(algorithm);
// Create read stream
const stream = fs.createReadStream(filePath);
// Handle stream events
stream.on('data', (data) => {
hash.update(data);
});
stream.on('end', () => {
const digest = hash.digest('hex');
resolve(digest);
});
stream.on('error', (error) => {
reject(error);
});
});
}
// Example usage (adjust file path as needed)
const filePath = 'example.txt';
// Create a test file if it doesn't exist
if (!fs.existsSync(filePath)) {
fs.writeFileSync(filePath, 'This is a test file for hashing.\n'.repeat(100));
console.log(`Created test file: ${filePath}`);
}
// Hash the file with different algorithms
Promise.all([
hashFile(filePath, 'md5'),
hashFile(filePath, 'sha1'),
hashFile(filePath, 'sha256')
])
.then(([md5Digest, sha1Digest, sha256Digest]) => {
console.log(`File: ${filePath}`);
console.log(`MD5: ${md5Digest}`);
console.log(`SHA-1: ${sha1Digest}`);
console.log(`SHA-256: ${sha256Digest}`);
})
.catch(error => {
console.error('Error hashing file:', error.message);
});