async for 循环导致函数静默终止

您好,我试图了解以下代码中发生的情况:


import fs from "fs";

import util from "util";

import split2 from "split2";


async function main() {

    const files = await fs.promises.readdir("..");

    for (const f of files) {

        const s = fs.createReadStream("../" + f);

        const ss = s.pipe(split2());

        s.on("error", (err) => {

            console.log(err);

        });

        for await (const l of ss) {

        }


        console.log(f);

    }

    console.log("Returning");

    return "Done";

}

main();

它基本上读取目录中的每个文件并迭代每个文件的行(通过使用 forawait 语法将可读流通过管道输送到 split2 库中。问题是,当文件确实是目录时,createReadStream 失败(随后什么也没有发生)奇怪的是,似乎一个错误导致主函数默默退出并在错误之前仅显示几个文件名。


.gitignore

app.js

[Error: EISDIR: illegal operation on a directory, read] {

  errno: -21,

  code: 'EISDIR',

  syscall: 'read'

}

如果我只是评论await for 循环,我会得到以下输出。


.gitignore

app.js

business

components

config

env.skeletron

node_modules

package-lock.json

Returning

[Error: EISDIR: illegal operation on a directory, read] {

  errno: -21,

  code: 'EISDIR',

  syscall: 'read'

}

[Error: EISDIR: illegal operation on a directory, read] {

  errno: -21,

  code: 'EISDIR',

  syscall: 'read'

}

[Error: EISDIR: illegal operation on a directory, read] {

  errno: -21,

  code: 'EISDIR',

  syscall: 'read'

}

[Error: EISDIR: illegal operation on a directory, read] {

  errno: -21,

  code: 'EISDIR',

  syscall: 'read'

}

[Error: EISDIR: illegal operation on a directory, read] {

  errno: -21,

  code: 'EISDIR',

  syscall: 'read'

}

[Error: EISDIR: illegal operation on a directory, read] {

  errno: -21,

  code: 'EISDIR',

  syscall: 'read'

}

[Error: EISDIR: illegal operation on a directory, read] {

  errno: -21,

  code: 'EISDIR',

  syscall: 'read'

}

[Error: EISDIR: illegal operation on a directory, read] {

  errno: -21,

  code: 'EISDIR',

  syscall: 'read'

}

  

这确实是完整的文件列表,并且各个错误不会停止外循环。我在 Ubuntu 机器上使用节点 v14.0.0 运行它。知道发生了什么事吗?我真的迷路了:-D


慕哥6287543
浏览 78回答 1
1回答

Helenr

您没有处理循环中的错误for await (const l of ss) {...}。当您尝试在目录上运行它时,您的for await循环将拒绝,并且由于您没有捕获或处理该拒绝,因此包含的async函数也将拒绝并且程序将停止。您可以尝试在循环中放置 try/catchfor await并查看是否有效。但是,我在流功能中发现了许多错误for await,甚至提交了一些错误。如果打开文件时出错或读取文件时出错,则会出现错误,因此此功能只是有错误,因此我决定不在我的代码中使用它。另请注意,您没有一个好的方法来从事件中传达错误,error因为您无法拒绝async嵌套事件处理程序内部的函数。总体而言,流及其事件与基于承诺的编程不能很好地融合。有多种方法可以承诺某些流事件,但要使流与承诺良好配合,还需要进行中。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript