Created
February 2, 2011 14:12
-
-
Save liangzan/807712 to your computer and use it in GitHub Desktop.
A Node.js script to remove all files in a directory recursively
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') | |
, 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 + '/'); | |
} | |
} | |
}); | |
}); | |
} | |
} | |
}); | |
} |
@iserdmi Thanks. I needed a version that wouldn't delete the directory itself.
Maybe it will be usefull for someone. Extend @guybedfrod function, to remove all in dir but not dir itself.
rmDir = function(dirPath, removeSelf) { if (removeSelf === undefined) removeSelf = true; try { var files = fs.readdirSync(dirPath); } catch(e) { return; } if (files.length > 0) for (var i = 0; i < files.length; i++) { var filePath = dirPath + '/' + files[i]; if (fs.statSync(filePath).isFile()) fs.unlinkSync(filePath); else rmDir(filePath); } if (removeSelf) fs.rmdirSync(dirPath); };
Call
rmDir('path/to/dir')
to remove all inside dir and dir itself. CallrmDir('path/to/dir', false)
to remove all inside, but not dir itself.
This is helpful. Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A bit more structured :)