下面列出了代码。问题是 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/