我是 Node.js 新手,正在使用 API。在流模块文档中,我遇到了“unpipe 事件”的示例(实际上是文档中两个示例的融合)。
const fs = require("fs);
const writable = fs.createWriteStream("write.txt");
const readable = fs.createReadStream("read.txt");
readable.pipe(writable);
setTimeout(function(){
console.log("Stop writing to file.txt");
readable.unpipe(writable);
console.log("Manually close the file stream");
writable.end();
}, 0);
writable.on("unpipe", function(src){
console.log("Something has stopped piping into the writer");
});
我无法理解以下 console.log 顺序:
"Stop writing to file.txt"
"Something has stopped piping into the writer"
"Manually close the file stream"
鉴于 setTimeout 回调正在运行 - 据我所知,这是事件循环的第一阶段 - “unpipe”事件的回调到底是如何在 setTimeout 回调完成之前开始运行的。
最初,我在零秒以上的时间后触发了 setTimeout,但是我发现总是首先调用 unpipe 回调。我推断我的计算机总是在 setTimeout 准备好之前首先读取文件。 (虽然我在文档中看不到任何关于完成写入文件引发“unpipe”事件的提及,但我认为这是有道理的)。然而,我无法解释上述程序流程是如何发生的。预先感谢您的帮助。
最佳答案
如 node.js documentation 所指定:
The
EventEmitter
calls all listeners synchronously in the order in which they were registered.
也就是说,当调用 .emit
时,它会同步运行所发出事件的所有监听器并调用它们。
请注意,如有必要,您可以将回调代码包装在 process.nextTick
中,以确保它始终异步运行,但在您的情况下,这可能是不必要的。
此外,对 .emit
的调用源(事件的发出)通常是异步的。
关于node.js - 意外的 Node.js 程序流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52392425/