Created
May 2, 2017 21:53
-
-
Save vietlq/eb1362dbe929366c3129865e0c74462f to your computer and use it in GitHub Desktop.
recursive directory delete with promises (using rsvp) in node.js
This file contains hidden or 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
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