我想遍历/images下所有的png文件,将他们的路径塞到一个数组中
目录结构
const Fs = require('fs');
const Path = require('path');
let imgPathArr = [];
// 获取 images 下所有的目录和文件
async function getAllFilePath(folderName) {
return new Promise((resolve) => {
let currentPath = Path.join(__dirname, folderName);
Fs.readdir(currentPath, (err, files) => {
files.forEach((name) => {
Fs.stat(Path.join(currentPath, name), function (err, stat) {
if (stat.isFile()) {
if (Path.extname(name) === ".png") {
console.log(Path.join(currentPath, name))
imgPathArr.push(Path.join(currentPath, name));
}
}
else {
getAllFilePath(Path.join(folderName, name));
}
})
});
resolve(imgPathArr);
});
});
}
async function run() {
let result = await getAllFilePath("images");
console.log(result);
}
run();
结果
这个await没有生效。
既然知道用await/async和promise,干嘛还用一堆callback,这是我自己测试的,可用,你可以看看