Skip to content

Instantly share code, notes, and snippets.

@yoavniran
Last active May 13, 2020 15:58
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save yoavniran/adbbe12ddf7978e070c0 to your computer and use it in GitHub Desktop.
Node async & recursive dir remove
"use strict";
var path = require("path"),
fs = require("fs");
module.exports = (function(){
/**
* recursively remove the fs structure starting from (and including) the path given in dirToRemove
* @param dirToRemove
* the path to remove
* @param callback
* will be called when all operations are done successfully or when an error occurs
*/
return function removeDir(dirToRemove, callback) {
var dirList = [];
var fileList = [];
function flattenDeleteLists(fsPath, callback) {
fs.lstat(fsPath, function (err, stats) {
if (err) {
callback(err);
return;
}
if (stats.isDirectory()) {
dirList.unshift(fsPath); //add to our list of dirs to delete after we're done exploring for files
fs.readdir(fsPath, function (err, files) {
if (err) {
callback(err);
return;
}
var currentTotal = files.length;
var checkCounter = function (err) {
if (currentTotal < 1 || err) {
callback(err);
}
};
if (files.length > 0) {
files.forEach(function (f) {
flattenDeleteLists(path.join(fsPath, f), function (err) {
currentTotal -= 1;
checkCounter(err);
});
});
}
checkCounter(); //make sure we bubble the callbacks all the way out
});
}
else {
fileList.unshift(fsPath); //add to our list of files to delete after we're done exploring for files
callback();
}
});
}
function removeItemsList(list, rmMethod, callback) {
var count = list.length;
if (count === 0){
callback();
return;
}
list.forEach(function (file) {
fs[rmMethod](file, function (err) {
count -= 1;
if (count < 1 || err) {
callback(err);
}
});
});
}
function onFinishedFlattening(err) {
if (err) {
callback(err);
return;
}
removeItemsList(fileList, "unlink", function (err) {//done exploring folders without errors
if (err) {
callback(err);
return;
}
removeItemsList(dirList, "rmdir", function (err) { //done deleting files without errors
callback(err); //done
});
});
}
flattenDeleteLists(dirToRemove, onFinishedFlattening);
};
})();
var removeDir = require("./node-remove-dir");
var startTime = Date.now();
removeDir("/tmp/test1", function (err) {
console.log("finished! in " + (Date.now() - startTime) + " ms - ", err);
});
@its-dibo
Copy link

you must delete dirs after all files deleted.
you may attempt to delete a dir before deleting it's content.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment