Created
September 18, 2012 19:38
-
-
Save chesles/3745340 to your computer and use it in GitHub Desktop.
Recursively removing a directory 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 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