Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save vikaskanani/c0e15faf108b8b944bc2d7c1014f2fbe to your computer and use it in GitHub Desktop.
Save vikaskanani/c0e15faf108b8b944bc2d7c1014f2fbe to your computer and use it in GitHub Desktop.
nodejs: remove empty directories recursively which are older than 2 days
function cleanEmptyFoldersRecursively(folder) {
var fs = require('fs');
var path = require('path');
var folderStat = fs.statSync(folder);
var isDir = folderStat.isDirectory();
if (!isDir) {
return;
}
var files = fs.readdirSync(folder);
if (files.length > 0) {
files.forEach(function(file) {
var fullPath = path.join(folder, file);
cleanEmptyFoldersRecursively(fullPath);
});
// re-evaluate files; after deleting subfolder
// we may have parent folder empty now
files = fs.readdirSync(folder);
}
if (files.length == 0) {
var cutoff = new Date().getTime() - ( 2 * 24 * 60 * 60 * 1000 ); // 2 days old
var folderCreatedDate = new Date(folderStat.mtime).getTime();
if(folderCreatedDate < cutoff) {
console.log("removing: ", folder);
fs.rmdirSync(folder);
return;
} else {
return;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment