【发布时间】:2019-02-22 20:02:55
【问题描述】:
我是 node.js 的新手,并且正在使用 API。在流模块文档中,我遇到了这个“unpipe event”示例(实际上是文档中两个示例的融合)。
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”事件的内容,但我认为这是有道理的)。但是,我无法终生解释上述程序流程是如何发生的。提前感谢您的帮助。
【问题讨论】:
-
事件处理回调同步发出
-
啊,谢谢。我刚刚使用事件发射器检查了浏览器中的客户端 JS,你所说的在那个例子中也是正确的。所以事件循环不会处理“事件处理程序”,对吗?
-
非常精确 - 它们由事件循环处理,但以同步方式处理,这意味着与您的 sn-p 中的
setTimeout处理程序在同一轮事件循环中 :) -
谢谢。接下来我将介绍“事件”模块,我想哈哈。祝大家好运。
标签: node.js