const crypto = require('crypto');
const fs = require('fs').promises;
const path = require('path');
/**
* Hashes the contents of a directory and its subdirectories.
* @param {string} dirPath The path to the directory to hash.
* @returns {Promise<string>} A promise that resolves to the directory hash.
* @throws {Error} If the directory does not exist.
*/
async function hashDirectory(dirPath) {
try {
const stats = await fs.stat(dirPath);
if (!stats.isDirectory()) {
throw new Error(`Not a directory: ${dirPath}`);
}
let contents = [];
try {
const files = await fs.readdir(dirPath);
for (const file of files) {
const filePath = path.join(dirPath, file);
const fileStats = await fs.stat(filePath);
if (fileStats.isDirectory()) {
// Recursively hash subdirectories
contents.push(await hashDirectory(filePath));
} else {
// Add file content to the hash
const fileContent = await fs.readFile(filePath, 'utf8');
contents.push(fileContent);
}
}
} catch (err) {
console.error(`Error reading directory ${dirPath}: ${err.message}`);
throw err;
}
// Concatenate and hash the contents
const combinedString = contents.join('\n'); //Separate files with newline for readability
const hash = crypto.createHash('sha256').update(combinedString).digest('hex');
console.log(`Hashes for directory ${dirPath}: ${hash}`); //Verbose logging
return hash;
} catch (err) {
console.error(`Error hashing directory ${dirPath}: ${err.message}`); //Verbose logging
throw err;
}
}
// Example Usage (replace with your directory path)
async function main() {
const directoryPath = process.argv[2]; //Get directory path from command line argument
if (!directoryPath) {
console.error("Please provide a directory path as a command line argument.");
process.exit(1);
}
try {
const hash = await hashDirectory(directoryPath);
console.log(`Final Hash: ${hash}`);
} catch (error) {
console.error("An error occurred:", error.message);
process.exit(1);
}
}
main();
Add your comment