Last active
December 27, 2016 21:08
-
-
Save camelaissani/ab4a9e6d69088d6f03a46ee2fd4fd112 to your computer and use it in GitHub Desktop.
Makes a recursive rmdir in nodejs
This file contains 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'); | |
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