Search code examples
node.jsnode.js-stream

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


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.


Solution

  • 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!