Skip to content

Instantly share code, notes, and snippets.

@chesles
Created September 18, 2012 19:38
Show Gist options
  • Save chesles/3745340 to your computer and use it in GitHub Desktop.
Save chesles/3745340 to your computer and use it in GitHub Desktop.
Recursively removing a directory in node.js
var fs = require('fs')
, path = require('path')
function rmdir(dir, callback) {
fs.readdir(dir, function rmfiles(err, files) {
if (err && err.code == 'ENOTDIR') {
return fs.unlink(dir, callback);
}
else if (err) {
return callback(err);
}
var count = files.length;
if (count == 0) {
return fs.rmdir(dir, callback);
}
files.forEach(function(file) {
var todel = path.join(dir, file);
rmdir(todel, function(err) {
count--;
if (count <= 0) {
fs.rmdir(dir, callback);
}
});
})
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment