Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@angrymarker angrymarker commented Jul 31, 2018

This worked great, thanks!

@fixpunkt

This comment has been minimized.

Copy link

@fixpunkt fixpunkt commented Jan 31, 2020

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

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