0

我想遍历/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没有生效。

fftu 114
2019-01-12 提问
4 个回答
1

已采纳

既然知道用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);
)();
2

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

0

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

0

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

撰写答案

推广链接