Created
May 13, 2015 23:38
-
-
Save lyzadanger/7397ce8f196abe9fa2ed to your computer and use it in GitHub Desktop.
Recursive delete all empty directory trees
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
'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