node.jsconnectionrequestabort

How to check if connection was aborted in node.js server


I'm making some long polling with node.js.
Basically, node.js server accepts request from the user and then checks for some updates. If there're no updates, it will check them after the timeout.
But what if user has closed his tab, or went to another page? In my case, the script continues working.
Is there a way in node.js to check or detect or to catch an event when user has aborted his request (closed the connection)?


Solution

  • Thanks to Miroshko's and yojimbo87's answers I was able to catch the 'close' event, but I had to make some additional tweaks.

    The reason why just catching 'close' event wasn't fixing my problem, is that when client sends the request to the node.js server, the server itself can't get information if the connection is still open until he sends something back to the client (as far as I understood - this is because of the HTTP protocol).
    So, the additional tweak was to write something to the response from time to time.
    One more thing that was preventing this to work, is that I had 'Content-type' as 'application/json'. Changing it to 'text/javascript' helped to stream 'white spaces' from time to time without closing the connection.
    In the end, I had something like this:

    var server = http.createServer(function(req,res){    
        res.writeHead(200, {'Content-type': 'text/javascript'});
    
        req.connection.on('close',function(){    
           // code to handle connection abort
        });
    
        /**
         * Here goes some long polling handler
         * that performs res.write(' '); from time to time
         */
    
        // some another code...
    });
    server.listen(NODE_PORT, NODE_LISTEN_HOST);
    

    My original code is much bigger, so I had to cut it a lot just to show the sensitive parts.

    I'd like to know if there are better solutions, but this is working for me at the moment.