When making requests in Node.JS to another HTTP server, you can listen for when the server closes the connection with request.on('close', function(){});. I’ve been searching for similar functionality within Node’s http.createServer(). I assumed that that request variable passed in to the callback had an on() function which I could call to listen for when the client closes the connection.
var http = require('http');
http.createServer(function(req, res) {
req.on('close', function() { console.log("Connection closed"); });
}).listen(80, '127.0.0.1');
However, after reading the 0.4.9 docs on streams, I noticed that under the close event it said:
Not all streams will emit this. (For example, an incoming HTTP request will not emit ‘close’.)
Is there a way to listen for client connection terminations from the server in Node?
Well, you could access the socket directly by doing:
However, doing this inside a request listener will bind the event for every request. So instead you should bind to the connection event:
EDIT:
Maybe I should have mentioned, yes, technically the socket object for an http server will carry a reference to the response on the
_httpMessageproperty. However, I would advise against using this as it is part of the internal API and is subject to change without any warning.It would be better to add your own property to get a reference to the last request made: