Skip to content

Instantly share code, notes, and snippets.

@vietlq
Created May 2, 2017 21:53
Show Gist options
  • Save vietlq/eb1362dbe929366c3129865e0c74462f to your computer and use it in GitHub Desktop.
Save vietlq/eb1362dbe929366c3129865e0c74462f to your computer and use it in GitHub Desktop.
recursive directory delete with promises (using rsvp) in node.js
var rsvp = require("rsvp")
var Promise = rsvp.Promise;
function cleardir(path) {
return new Promise(function(resolve, reject) {
fs.readdir(path, function(err, dir) {
if (err) {
reject(err);
return;
}
resolve(rsvp.all(dir.map(function(item) {
console.log("deleting", item);
return rm(pathutils.join([path, item]));
})));
});
});
}
function rm(path) {
return new Promise(function(resolve, reject) {
fs.stat(path, function(err, stat) {
if (err) {
reject(err);
return;
}
if (stat.isFile()) {
fs.unlink(path, function(err) {
if (err) {
reject(err);
} else {
resolve(path);
}
});
} else if (stat.isDirectory()) {
cleardir(path).then(function() {
fs.rmdir(path, function(err) {
if (err) {
reject(err);
} else {
resolve(path);
}
});
});
} else {
reject(new Error(path + " is not a file or directory"));
}
});
});
}
exports.rm = rm;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment