Memory leak when using threads in Node.js?

Suppose I have a simple http server, for example:

var http = require('http'); http.createServer(function (req, res) { req.on('data', function (data) { console.log('Got some data: ' + data); }); req.on('end', function () { console.log('Request ended!'); }); res.end('Hello world!'); }).listen(3000); 

So basically the default example 101, nothing special so far - except that I subscribe to the data and end event of the req read stream. Now I wonder, do I need to unsubscribe from these events when I no longer need them?

Or do they automatically clear when the read stream ends?

Can such a code cause a memory leak?

+6
source share
1 answer

(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 .

+15
source

Source: https://habr.com/ru/post/956586/


All Articles