Skip to content

Instantly share code, notes, and snippets.

@scripting
Created March 25, 2016 13:53
Show Gist options
  • Save scripting/f78fc5df8125df056f05 to your computer and use it in GitHub Desktop.
Save scripting/f78fc5df8125df056f05 to your computer and use it in GitHub Desktop.
Recursively delete a directory and all its subs and files it contains.
function fsDeleteDirectory (folderpath, callback) { //3/25/16 by DW
if (folderpath [folderpath.length - 1] != "/") {
folderpath += "/";
}
fs.readdir (folderpath, function (err, list) {
if (err) {
console.log ("fsDeleteDirectory: err.message == " + err.message);
}
else {
function doListItem (ix) {
if (ix < list.length) {
var f = folderpath + list [ix];
fs.stat (f, function (err, stats) {
if (err) {
doListItem (ix + 1);
}
else {
if (stats.isDirectory ()) { //dive into the directory
fsDeleteDirectory (f, function () {
doListItem (ix + 1);
});
}
else {
fs.unlink (f, function () {
doListItem (ix + 1);
});
}
}
});
}
else {
fs.rmdir (folderpath, function () {
if (callback !== undefined) {
callback ();
}
});
}
}
doListItem (0);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment