【问题标题】:Node.js Http server, readstream end event firing console.log twiceNode.js Http 服务器,readstream 结束事件触发 console.log 两次
【发布时间】: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


    【解决方案1】:

    每个响应的浏览器都在寻找 favicon.ico ,在这种情况下,因为您没有发送带有 <link rel="icon" href="favicon.ico" type="image/x-icon"/> 的 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 的情况呢?您仍然应该以某种方式响应该请求...
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-26
      • 1970-01-01
      • 2016-06-18
      • 2015-05-10
      • 1970-01-01
      • 2013-05-29
      • 1970-01-01
      • 2021-12-15
      相关资源
      最近更新 更多