Skip to content

Instantly share code, notes, and snippets.

@jakub-g
Created April 3, 2015 15:31
Show Gist options
  • Save jakub-g/5903dc7e4028133704a4 to your computer and use it in GitHub Desktop.
Save jakub-g/5903dc7e4028133704a4 to your computer and use it in GitHub Desktop.
nodejs: remove empty directories recursively
function cleanEmptyFoldersRecursively(folder) {
var fs = require('fs');
var path = require('path');
var isDir = fs.statSync(folder).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) {
console.log("removing: ", folder);
fs.rmdirSync(folder);
return;
}
}
@rnag
Copy link

rnag commented Feb 3, 2023

@arnoson Very nice. In case anyone needs a version which excludes certain directories from the traversal (such as the ubiquitous node_modules/ directory), here is a slight revision I made -- this should work for Typescript/Node:
https://gist.github.com/rnag/a5e8dcea68979a5df4a946e41f75ea97

Measuring performance, I noted a huge improvement in my case. ~100 milliseconds down to ~1 millisecond. The reason is that otherwise it was traversing down a node_modules subfolder which had a ton of folders underneath it that it need to separately check.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment