检查是否存在多个文件夹?
Check if multiple folders exist?
我使用 fs.stat 检查文件夹是否存在:
fs.stat('path-to-my-folder', function(err, stat) {
if(err) {
console.log('does not exist');
}
else{
console.log('does exist');
}
});
有没有一种方法可以只使用一种方法来检查多条路径的存在?
不,文件系统API 没有检查是否存在多个文件夹的功能。您只需多次调用 fs.stat()
函数即可。
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')
您可以将其调整为在不同点失败等等,但您已经了解了总体思路。
我使用 fs.stat 检查文件夹是否存在:
fs.stat('path-to-my-folder', function(err, stat) {
if(err) {
console.log('does not exist');
}
else{
console.log('does exist');
}
});
有没有一种方法可以只使用一种方法来检查多条路径的存在?
不,文件系统API 没有检查是否存在多个文件夹的功能。您只需多次调用 fs.stat()
函数即可。
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')
您可以将其调整为在不同点失败等等,但您已经了解了总体思路。