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;
}
}
@angrymarker
Copy link

This worked great, thanks!

@fixpunkt
Copy link

I just ended up porting this to async, in case anyone needs it: https://gist.github.com/fixpunkt/fe32afe14fbab99d9feb4e8da7268445

@bit-less
Copy link

Very clever with the second if statement and reloading the files before. I was banging my head against reverse recursion issues, and that solved it. Nice work!

@arnoson
Copy link

arnoson commented Nov 15, 2022

Thanks! I ported it to an ES module (and shortened it a bit): https://gist.github.com/arnoson/3237697e8c61dfaf0356f814b1500d7b

@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