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; | |
} | |
} |
Thanks! I ported it to an ES module (and shortened it a bit): https://gist.github.com/arnoson/3237697e8c61dfaf0356f814b1500d7b
@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
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!