2016-06-19 266 views
0

以下代碼可幫助遞歸刪除文件夾。它刪除整個文件夾。遞歸刪除文件夾但排除命名文件夾

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,folderName2folderName3folderName1folderName2及其所有文件將不會被刪除,如果我以下面的方式聲明。

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

你想在排除列表目錄被完全忽略,或者也走過有文件/在其中目錄還刪除,如果不排除? – Nicholas

回答

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 
+0

嗨,我通過使用'deleteFolderRecursive(path,['folderName1'])',但它仍然導致整個文件夾被刪除。它不排除folderName1。在我看來,只要第二個參數被定義,shouldDelete將返回true – vincentsty

+0

試試這個'deleteFolderRecursive('folderName1',['folderName1'])'並確認它刪除了文件夾,它不應該刪除,如果它 - 錯誤的東西 –

+0

嗨它不刪除文件夾通過使用'deleteFolderRecursive('folderName1',['folderName1'])''。我當前的文件夾hierarychy是這樣的:'www/parentFolder/folderName1',所以我所做的就是調用'deleteFolderRecursive('../../ www/parentFolder',['folderName1'])''。不知道我是否以錯誤的方式使用它,但整個父文件夾被刪除。 – vincentsty