2016-11-11 96 views
0

我用fs.stat檢查一個文件夾是否存在:檢查是否存在多個文件夾?

fs.stat('path-to-my-folder', function(err, stat) { 
    if(err) { 
     console.log('does not exist'); 
    } 
    else{ 
     console.log('does exist'); 
    } 
}); 

有沒有一種方法來檢查的多條路徑只使用一個方法是否存在?

回答

1

不,文件系統API沒有檢查多個文件夾是否存在的功能。您只需要多次撥打fs.stat()函數。

2

fs沒有開箱即用的任何東西,但您可以創建一個函數來執行此操作。

function checkIfAllExist (paths) { 
    return Promise.all(
    paths.map(function (path) { 
     return new Promise(function (resolve, reject) { 
     fs.stat(path, function (err, stat) { 
      err && reject(path) || resolve() 
     }); 
     }); 
    })) 
); 
}; 

你會使用這個像這樣:

checkIfAllExist([path1, path2, path3]) 
    .then(() => console.log('all exist')) 
    .catch((path) => console.log(path + ' does not exist') 

你可以調整它的不同點和諸如此類的東西失敗,但你得到的總體思路。

+0

更短,也許更乾淨:'paths.map(path => new Promise(...))' –

+0

您是否暗示只使用ES6格式?我通常會這樣做,但是我保持原來問題的格式。在ES6格式中看起來更乾淨。 – samanime

+0

是的。 BTW'函數(err,stat)=> {'是無效的語法。 –

相關問題