Javascript Node.js Http服务器,readstream end event firing console.log两次
代码如下所示。问题是console.log()触发了两次,这表明rs.end触发了两次,尽管我只将其注册为fire一次。如果我注释掉res.end(),它只会触发一次,所以我知道对res.end的调用也会导致rs.end触发,我只是不明白为什么 我认识到这可能只是对事件系统或服务器流对象的误解,这两个我都没有深入研究过 但有点奇怪的是,如果我将console.log更改为res.write,以便它将其写入浏览器,它只将其写入浏览器一次,即使调用了res.end() 提前感谢您提供的任何帮助Javascript Node.js Http服务器,readstream end event firing console.log两次,javascript,node.js,stream,streaming,Javascript,Node.js,Stream,Streaming,代码如下所示。问题是console.log()触发了两次,这表明rs.end触发了两次,尽管我只将其注册为fire一次。如果我注释掉res.end(),它只会触发一次,所以我知道对res.end的调用也会导致rs.end触发,我只是不明白为什么 我认识到这可能只是对事件系统或服务器流对象的误解,这两个我都没有深入研究过 但有点奇怪的是,如果我将console.log更改为res.write,以便它将其写入浏览器,它只将其写入浏览器一次,即使调用了res.end() 提前感谢您提供的任何帮助 re
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
自动发送的请求。每个响应的浏览器都在查找favicon.ico,在这种情况下,因为您没有发送带有
的html,而是发送另一个查找该请求的请求,如果您试图避免它,您可以这样做:
var http = require('http');
var fs = require('fs');
http.createServer(function(req, res) {
var rs;
if(req.url !== "/favicon.ico") {
rs = 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(3000);
如果请求的是favicon,情况会怎样?你仍然应该以某种方式回应这个请求。。。