Skip to content

Instantly share code, notes, and snippets.

@camelaissani
Last active December 27, 2016 21:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save camelaissani/ab4a9e6d69088d6f03a46ee2fd4fd112 to your computer and use it in GitHub Desktop.
Save camelaissani/ab4a9e6d69088d6f03a46ee2fd4fd112 to your computer and use it in GitHub Desktop.
Makes a recursive rmdir in nodejs
var fs = require('fs');
function rmdirSync(dir) {
var currentDirToRead,
directoriesFound,
nextDirToReadIndex;
if (!fs.existsSync(dir)) {
return;
}
currentDirToRead = dir;
directoriesFound = [dir];
while (true) {
fs.readdirSync(currentDirToRead).forEach(function(name) {
var path = currentDirToRead+'/'+name;
var stat = fs.lstatSync(path);
if (stat.isDirectory()) {
directoriesFound.push(path);
} else {
fs.unlinkSync(path);
}
});
nextDirToReadIndex = directoriesFound.indexOf(currentDirToRead) + 1;
if (nextDirToReadIndex >= directoriesFound.length) {
break;
}
currentDirToRead = directoriesFound[nextDirToReadIndex];
}
directoriesFound.reverse();
directoriesFound.forEach(function(path) {
fs.rmdirSync(path);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment