Last updated
Directory Comparison
Directory comparison identifies differences between two folder structures: files that exist in one but not the other, files with the same name but different content, and files that are identical. This is useful for syncing backups, comparing deployment artifacts, and auditing file system changes.
Comparison Strategies
| Method | Speed | Accuracy |
|---|---|---|
| Name only | Fastest | Low (misses content changes) |
| Name + size | Fast | Medium |
| Name + size + date | Fast | Good |
| Content hash (MD5/SHA) | Slow | Perfect |
Directory Diff with Node.js
JavaScript
import { readdir, stat, readFile } from 'fs/promises';
import { createHash } from 'crypto';
import path from 'path';
async function hashFile(filepath) {
const content = await readFile(filepath);
return createHash('md5').update(content).digest('hex');
}
async function listFiles(dir, base = dir) {
const entries = await readdir(dir, { withFileTypes: true });
const files = {};
for (const entry of entries) {
const full = path.join(dir, entry.name);
const rel = path.relative(base, full);
if (entry.isDirectory()) {
Object.assign(files, await listFiles(full, base));
} else {
files[rel] = await hashFile(full);
}
}
return files;
}
async function compareDirectories(dir1, dir2) {
const [files1, files2] = await Promise.all([listFiles(dir1), listFiles(dir2)]);
const onlyIn1 = Object.keys(files1).filter(f => !files2[f]);
const onlyIn2 = Object.keys(files2).filter(f => !files1[f]);
const modified = Object.keys(files1).filter(f => files2[f] && files1[f] !== files2[f]);
return { onlyIn1, onlyIn2, modified };
}