你好,我正在尝试理解下面这段代码中发生了什么:
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();
它基本上读取目录中的每个文件并遍历每个文件的行(通过使用for await语法将可读流通过管道传输到split2库中。问题是,当文件确实是一个目录时,createReadStream会失败(随后没有任何内容通过管道传输到下游)。奇怪的是,似乎是一个单一的错误导致main函数静默退出,并且在错误之前只显示了几个文件名。
.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机器上用node v14.0.0运行它。知道是怎么回事吗?我真的迷路了:-D
发布于 2020-11-18 16:39:07
您没有在for await (const l of ss) {...}
循环中处理错误。当你试图在一个目录上运行它时,你的for await
循环将会拒绝,因为你不能捕获或处理这个拒绝,所以包含的async
函数也会拒绝,程序也会停止。
您可以尝试在for await
循环周围放置一个try/catch,看看是否有效。但是,我在streams的for await
特性中发现了许多bug,甚至提交了一些bug。如果打开文件时出错或读取文件时出错,就会出现bug,所以这个特性有bug,因此我决定不在我的代码中使用它。
另外,请注意,由于不能从嵌套的事件处理程序中拒绝async
函数,因此没有一种很好的方法来从error
事件传回错误。总体而言,流及其事件与基于promise的编程不能很好地混合。有一些方法可以简化一些流事件,但要让流与promises一起很好地工作,这是一个正在进行的工作。
https://stackoverflow.com/questions/64897131
复制相似问题