Skip to content

Instantly share code, notes, and snippets.

@lyzadanger
Created May 13, 2015 23:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lyzadanger/7397ce8f196abe9fa2ed to your computer and use it in GitHub Desktop.
Save lyzadanger/7397ce8f196abe9fa2ed to your computer and use it in GitHub Desktop.
Recursive delete all empty directory trees
'use strict';
var walk = require('walkdir');
var fs = require('fs');
var path = require('path');
var extfs = require('extfs');
var deleteEmptyPath = function deleteEmptyPath(delPath, cb) {
extfs.isEmpty(delPath, function (isEmpty) {
if (isEmpty) {
fs.rmdir(delPath, function(err) {
console.log('removed empty directory', delPath);
// Walk up and check for emptiness until
// we find a non-empty directory, deleting all the way
deleteEmptyPath(path.dirname(delPath), cb);
});
} else {
cb();
}
});
};
var killDirs = function(emptyDirs, done) {
if (emptyDirs.length) {
deleteEmptyPath(emptyDirs.pop(), function() {
// The path and any empty parents have been removed
// Call on the next deep path
killDirs(emptyDirs, done);
});
} else {
done();
}
};
(function deleteEmptyDirTrees() {
var emptyDirs = [];
var walker = walk('./stuff');
// This will emit on an empty directory
// but not on the empty directory's parents
// because they are not empty YET
walker.on('empty', function (emptyPath, stat) {
emptyDirs.push(emptyPath);
});
walker.on('end', function() {
killDirs(emptyDirs, function() {
// Done.
});
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment