递归删除文件夹但排除命名文件夹

时间:2016-06-19 13:30:13

标签: javascript node.js

以下代码有助于递归删除文件夹。它会删除整个文件夹。

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的文件夹具有子文件夹名称folderName1folderName2folderName3。如果我按以下方式声明,folderName1folderName2及其所有文件都不会被删除。

var deleteFolderRecursive = function (removePath, excludeDirArray) {
    // code here
}
deleteFolderRecursive(path, ['folderName1', 'folderName2']);

1 个答案:

答案 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