如何异步运行 node.js FS 函数?

时间:2021-05-07 02:19:49

标签: javascript node.js asynchronous fs

我对使用 fs 和 async/await 有点困惑。 我有一个名为 tests 的文件夹,其中包含 6 个文件夹,每个文件夹都包含大量图像。我需要遍历每个图像并将其文件名保存到一个数组中。这是文件夹结构:

|-tests
 |---test1
 |---test2
 |---test3
 |---test4
 |---test5
 |---test6

这是我写的代码:

让数组 = [];

fs.readdir(sourcePathDesktopWin,  (err, folders) => {
  console.log('folders: ', folders);
  folders.forEach( (folder) => {
    fs.readdir(
      `${sourcePathDesktopWin}/${folder}/`,
       (err, files) => {
        files.forEach( async (file) => {
          await array.push(file);
        });
      }
    );
  });
});

console.log('array: ', array);

console.log 显示为空,因为它在 fs 函数完成之前运行。 我在这里有两个问题:

  1. 如何在 fs 函数完成运行后触发 console.log?
  2. 编写此函数的更好方法是什么?

谢谢。

0 个答案:

没有答案
相关问题