node.js异步遍历文件夹失败

我想遍历/images下所有的png文件,将他们的路径塞到一个数组中

目录结构

clipboard.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();

结果
clipboard.png

这个await没有生效。

阅读 3k
4 个回答

既然知道用await/async和promise,干嘛还用一堆callback,这是我自己测试的,可用,你可以看看

const fs = require('fs');
const path = require('path');
const { promisify } = require('util');

const readdir = promisify(fs.readdir);
const stat = promisify(fs.stat);

let imgPathArr = [];

async function loopFile(folder) {
  let files = await readdir(folder);

  for(let i=0; i<files.length; i++) {
        let file = await stat(path.join(folder, files[i]));
        if(file.isFile()) {
            imgPathArr.push(path.join(folder, files[i]));
        }else{
            await loopFile(path.join(folder, files[i]));
        }
  }
}

(async () => {
  await loopFile(path.join(__dirname, 'files'));
  console.log(imgPathArr);
)();

foreach里面不是还有一个异步调用吗,在外面resolve肯定不行啊

循环中存在async,推荐使用for循环

你这个不是代码的问题。是你的nodemon观察文件改动导致。 你试试把nodemon先关闭。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题