Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 417
AbstractVoid Avatar asked Sep 08 '11 13:09

AbstractVoid


People also ask

How do I check Nodejs server status?

To check the node server running by logging in to the system In windows you can simply go to the Task Manager and check for node in the application list. If it is there then it is running in the machine.

What is http createServer in node JS?

The http. createServer() method turns your computer into an HTTP server. The http. createServer() method creates an HTTP Server object. The HTTP Server object can listen to ports on your computer and execute a function, a requestListener, each time a request is made.

Is node js still relevant in 2021?

js for backend development is still a choice of Netflix, NASA, Microsoft, and other tech giants. Undoubtedly, it's not as popular as React. js or jQuery, but it allows companies to house more full-stack web developers than any other framework in the world. According to another survey conducted in 2021, Node.

Is node js still relevant 2020?

Node. js development has become very popular over the last four years and continues to stand the competition in 2022 making startups worldwide choose it over other available options.


1 Answers

You need to use req.on('close', function(err) { ... }); instead of req.connection.on('close', function(err) { ... });

There is a very important distinction. req.on() adds a listener to this request while req.connection.on(), you add a listener to the (keep-alive) connection between the client and the server. If you use req.connection.on(), every time the client re-uses a connection, you add one more listener to the same connection. When the connection is finally aborted, all listeners are fired.

Function scoping typically keeps you safe from this screwing up your server logic, but it's a dangerous thing nevertheless. Fortunately at least NodeJS 0.10.26 is smart enough to warn the user of this:

(node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit. Trace:    at Socket.EventEmitter.addListener (events.js:160:15)   at Socket.Readable.on (_stream_readable.js:689:33)   ... 
like image 51
Sampo Savolainen Avatar answered Sep 30 '22 15:09

Sampo Savolainen