Skip to content

Instantly share code, notes, and snippets.

@heruputra
Forked from liangzan/recursiveRemoveFiles.js
Created December 10, 2013 17:19
Show Gist options
  • Save heruputra/7894384 to your computer and use it in GitHub Desktop.
Save heruputra/7894384 to your computer and use it in GitHub Desktop.
var fs = require('fs')
, path = require('path')
, _ = require('underscore');
var rootPath = "/path/to/remove";
removeDirForce(rootPath);
// path should have trailing slash
function removeDirForce(dirPath) {
fs.readdir(dirPath, function(err, files) {
if (err) {
console.log(JSON.stringify(err));
} else {
if (files.length === 0) {
fs.rmdir(dirPath, function(err) {
if (err) {
console.log(JSON.stringify(err));
} else {
var parentPath = path.normalize(dirPath + '/..') + '/';
if (parentPath != path.normalize(rootPath)) {
removeDirForce(parentPath);
}
}
});
} else {
_.each(files, function(file) {
var filePath = dirPath + file;
fs.stat(filePath, function(err, stats) {
if (err) {
console.log(JSON.stringify(err));
} else {
if (stats.isFile()) {
fs.unlink(filePath, function(err) {
if (err) {
console.log(JSON.stringify(err));
}
});
}
if (stats.isDirectory()) {
removeDirForce(filePath + '/');
}
}
});
});
}
}
});
}
@dscape
Copy link

dscape commented Sep 2, 2014

This was used to cheat a test. Random curiosity :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment