3

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.

  • I'm not sure, but what about trying to abort the request before it's finished? Forgive me if I'm saying bull shit – gustavohenke Nov 20 '13 at 13:44
  • you are right, maybe 'close' is fired, when the underlying connection is closed before the response is sent? –  Nov 20 '13 at 14:01
  • 1
    Try it, add some seconds of delay and see what happens – gustavohenke Nov 20 '13 at 14:07
  • @gustavohenke It's a good question because the docs http://nodejs.org/api/http.html#http_event_close_2 are not explicit about it. This question and answer helped. It would make more sense to have the close event fire anyway, I often leave underlying connections open for efficiency. A more appropriate term would be the 'abort' event. – dot slash hack May 11 '14 at 18:54

1 Answers1

7

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!

Community
  • 1
  • 1