如何在异步/等待中使用klaw?

时间:2018-10-19 13:42:06

标签: node.js async-await

我试图递归获取目录中所有Java文件的列表。我正在尝试使用Klaw,但似乎无法使其与async/await一起使用:

const files: string[] = [];
await klaw(myDir, { 
    filter: (item: any) => { return path.extname(item.path) === ".java"; }
}).on("data", (item) => { files.push(item.path); });

if (!files.length)
    console.log("Directory contains no java files");

但是,我在过滤器功能完成之前将if语句置于最底端。我不知道如何纠正它。

1 个答案:

答案 0 :(得分:0)

假设您的代码在async函数中正确运行。您可以执行以下操作

// this code should be inside async function to use await keyword
const run = async () => {
  const files: string[] = await new Promise<string[]>((resolve, reject) => {
    const files: string[] = [];
    klaw(myDir, {
      filter: (item: any) => {
        return path.extname(item.path) === ".java";
      }
    })
      .on("data", item => {
        files.push(item.path);
      })
      .on("end", () => resolve(files))
      .on("error", reject);
  });

  if (!files.length) console.log("Directory contains no java files");
};

或使用一些适合您的软件包。例如stream-to-promise

Playground Link

相关问题