node.js http.IncomingMessage does not fire 'close' event

我的梦境 提交于 2020-01-01 16:52:50

问题


When does the http.IncomingMessage fire its 'close' event?

According to the documentation it should occur when the underlaying connection was closed. However, it is never called for the following example code (I made sure it is not caused by keep-alive):

var http = require('http'),
    fs = require('fs');

var server = http.createServer(function(req, res) {
    res.shouldKeepAlive = false;
    req.on("end", function() {
        console.log("request end");
    });
    req.on("close", function() {
        console.log("request close");    // Never called
    });
    res.end("Close connection");
});
server.listen(5555);

I'm using node.js v0.10.22.


回答1:


The 'close' event is fired, when the underlying connection was closed before the response was sent.

Can be tested using the following server code and aborting the request midway through.

var http = require('http'),
    fs = require('fs');

var server = http.createServer(function(req, res) {
    res.shouldKeepAlive = false;
    req.on("end", function() {
        console.log("request end");
    });
    req.on("close", function() {
        console.log("request close");    // Called, when connection closed before response sent
    });

    setTimeout(function () {
        res.end("Close connection");
    }, 5000); // Wait some time to allow user abort
});
server.listen(5555);

Thanks to gustavohenke!



来源:https://stackoverflow.com/questions/20097255/node-js-http-incomingmessage-does-not-fire-close-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!