【发布时间】:2015-01-09 15:31:19
【问题描述】:
代码如下所示。问题是 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);
【问题讨论】:
标签: javascript node.js stream streaming