以下代码有助于递归删除文件夹。它会删除整个文件夹。
var deleteFolderRecursive = function(removePath) {
if( fs.existsSync(removePath) ) {
fs.readdirSync(removePath).forEach(function(file,index){
var curPath = path.join(removePath, file);
if(fs.lstatSync(curPath).isDirectory()) {
deleteFolderRecursive(curPath);
} else { // delete file
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(removePath);
}
};
如何将其扩展为递归删除文件夹,但按文件夹名称排除某些文件夹。假设名为parentFolder
的文件夹具有子文件夹名称folderName1
,folderName2
,folderName3
。如果我按以下方式声明,folderName1
和folderName2
及其所有文件都不会被删除。
var deleteFolderRecursive = function (removePath, excludeDirArray) {
// code here
}
deleteFolderRecursive(path, ['folderName1', 'folderName2']);
答案 0 :(得分:1)
var deleteFolderRecursive = function(removePath, exclusive) {
var shouldDelete = function(pathUrl) {
if(exclusive && exclusive.length){
return exclusive.indexOf(pathUrl) === -1;
}
return true;
}
if(fs.existsSync(removePath) && shouldDelete(removePath)) { // <-- use it here
fs.readdirSync(removePath).forEach(function(file,index){
var curPath = path.join(removePath, file);
if(fs.lstatSync(curPath).isDirectory()) {
deleteFolderRecursive(curPath);
} else { // delete file
if(shouldDelete(file)) { // <-- optionally use it here
fs.unlinkSync(curPath); // if you want also files to not be deleted
}
}
});
fs.rmdirSync(removePath);
}
};
deleteFolderRecursive(path, ['folderName1', 'folderName1', 'myFile.txt']); // <-- also file