1. const crypto = require('crypto');
  2. const fs = require('fs').promises;
  3. const path = require('path');
  4. /**
  5. * Hashes the contents of a directory and its subdirectories.
  6. * @param {string} dirPath The path to the directory to hash.
  7. * @returns {Promise<string>} A promise that resolves to the directory hash.
  8. * @throws {Error} If the directory does not exist.
  9. */
  10. async function hashDirectory(dirPath) {
  11. try {
  12. const stats = await fs.stat(dirPath);
  13. if (!stats.isDirectory()) {
  14. throw new Error(`Not a directory: ${dirPath}`);
  15. }
  16. let contents = [];
  17. try {
  18. const files = await fs.readdir(dirPath);
  19. for (const file of files) {
  20. const filePath = path.join(dirPath, file);
  21. const fileStats = await fs.stat(filePath);
  22. if (fileStats.isDirectory()) {
  23. // Recursively hash subdirectories
  24. contents.push(await hashDirectory(filePath));
  25. } else {
  26. // Add file content to the hash
  27. const fileContent = await fs.readFile(filePath, 'utf8');
  28. contents.push(fileContent);
  29. }
  30. }
  31. } catch (err) {
  32. console.error(`Error reading directory ${dirPath}: ${err.message}`);
  33. throw err;
  34. }
  35. // Concatenate and hash the contents
  36. const combinedString = contents.join('\n'); //Separate files with newline for readability
  37. const hash = crypto.createHash('sha256').update(combinedString).digest('hex');
  38. console.log(`Hashes for directory ${dirPath}: ${hash}`); //Verbose logging
  39. return hash;
  40. } catch (err) {
  41. console.error(`Error hashing directory ${dirPath}: ${err.message}`); //Verbose logging
  42. throw err;
  43. }
  44. }
  45. // Example Usage (replace with your directory path)
  46. async function main() {
  47. const directoryPath = process.argv[2]; //Get directory path from command line argument
  48. if (!directoryPath) {
  49. console.error("Please provide a directory path as a command line argument.");
  50. process.exit(1);
  51. }
  52. try {
  53. const hash = await hashDirectory(directoryPath);
  54. console.log(`Final Hash: ${hash}`);
  55. } catch (error) {
  56. console.error("An error occurred:", error.message);
  57. process.exit(1);
  58. }
  59. }
  60. main();

Add your comment