Created
April 3, 2015 15:31
-
-
Save jakub-g/5903dc7e4028133704a4 to your computer and use it in GitHub Desktop.
nodejs: remove empty directories recursively
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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.