[英]Why i can't push files in array?
我有一個遞歸查找文件的函數。 如果指定了類型 D,我只想將文件夾添加到數組中。 如果輸入 F 則只有文件。 它適用於文件搜索。 但是如果輸入 D 則不能添加任何內容,盡管可以輸出到控制台。 為什么我不能添加到數組中,我該如何修復它
const type = T or D
const walk = (dir, done) => {
let results = [];
return new Promise((resolve, reject) => {
fs.readdir(dir, (err, list) => {
if (err) return done(err);
let pending = list.length;
if (!pending) return done(null, results);
list.forEach((file) => {
file = path.join(dir, file);
fs.stat(file, function (err, stat) {
if (stat && stat.isDirectory()) {
if (type && type === 'D') {
console.log(file)
results.push(file);
}
walk(file, (err, res) => {
results.push(...res);
if (!--pending) done(null, results);
});
} else {
if (type === 'F') {
results.push(file);
if (!--pending) done(null, results);
}
}
});
});
});
})
};
walk(baseDir, (err, results) => {
if (err) throw err;
console.log(results);
});
當type
為D
,您當前僅在if (stat && stat.isDirectory())
塊內遞減pending
,但pending
的數量還取決於目錄中的文件數,因為let pending = list.length;
.
解決它的一種方法是在else
內遞減pending
,無論如何:
} else {
if (type === 'F') {
results.push(file);
}
if (!--pending) done(null, results);
}
或者,為了更干凈並避免一些回調地獄,使用async
函數並改為await
,然后您可以使用Promise.all
而不是手動檢查索引(這很乏味並且容易出錯)。 這也使函數正確返回一個 Promise(當done
沒有通過時):
const walk = async (dir, done) => {
try {
const list = await readdir(dir);
const resultsArr = await Promise.all(list.map(async (fileName) => {
const filePath = path.join(dir, fileName);
const stats = await stat(filePath);
if (stats.isDirectory()) {
if (type === 'D') {
return [filePath, ...await walk(filePath)];
}
return walk(filePath);
} else if (!stats.isDirectory() && type === 'F') {
return filePath;
}
}));
const flatResults = resultsArr.flat().filter(Boolean);
if (done) {
done(null, flatResults);
}
return flatResults;
} catch (err) {
if (done) {
done(err);
} else {
throw err;
}
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.