gpt4 book ai didi

javascript - Node.js Http 服务器,readstream 结束事件触发 console.log 两次

转载 作者:行者123 更新时间:2023-12-02 16:48:33 26 4
gpt4 key购买 nike

下面列出了代码。问题是 console.log() 触发了两次,表明 rs.end 触发了两次,即使我只将其注册为触发一次。如果我注释掉 res.end() 它只会触发一次,所以我知道对 res.end 的调用也会导致 rs.end 触发,我只是不明白为什么。

我认识到这可能只是对事件系统或服务器流对象的误解,我对这两者都没有深入研究。

但有点奇怪的是,如果我将 console.log 更改为 res.write 以便将其写入浏览器,则即使使用 res.end() ,它也只会将其写入浏览器一次被召唤。

预先感谢您提供的任何帮助!

require('http').createServer(function(req, res) {

var rs = require('fs').createReadStream('sample.txt');

//Set the end option to false to prevent res.end() being automatically called when rs ends.
rs.pipe(res, { end: false });

rs.once('end', function() {
console.log('Read stream completed');
res.end();
});

}).listen(8080);

最佳答案

您很可能会看到两个单独的 http 请求:一个是您显式发送的请求,另一个是浏览器为 /favicon.ico 自动发送的请求。

关于javascript - Node.js Http 服务器,readstream 结束事件触发 console.log 两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26892759/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com