(This answer contains links to parts of the revelant node.js source code)
Before answering your question, tell us about events. When you do this:
emitter.on('an-event', listener);
listener added to the list attached to emitter . Later, when emitter fires an event, it notifies all listeners who subscribe to this event by iterating through the list. The magic of node.js event emitters is that you yourself do not declare or manage this list.
However, when you call .on() , you create a back-reference emitter -> listener. This link will prevent the GC listener from collecting and create a “leak” if you never unsubscribe.
This does not happen often with node.js, because, as a rule, emitters are destroyed in front of the listeners, but the real case when this happens is when you have a long connection (I think the Twitter Streaming API), which sometimes reconnects. If you do not unregister the events, you may receive events from the old connection and think that they apply to the new one. This may make you think that the new connection is closed.
node.js will print the infamous “leak detection” message when it thinks you might forget to unregister listeners.
Back to your example:
This will not lead to a leak, because the socket (req + res) will be destroyed first. Since it is an emitter, node.js will force remove all listeners .
source share