-
-
Save jakub-g/5903dc7e4028133704a4 to your computer and use it in GitHub Desktop.
| 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; | |
| } | |
| } |
I just ended up porting this to async, in case anyone needs it: https://gist.github.com/fixpunkt/fe32afe14fbab99d9feb4e8da7268445
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!
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.
This worked great, thanks!