Nodejs event handling

Below is my nodejs code

var emitter = require('events'), eventEmitter = new emitter.EventEmitter(); eventEmitter.on('data', function (result) { console.log('Im From Data'); }); eventEmitter.on('error', function (result) { console.log('Im Error'); }); require('http').createServer(function (req, res) { res.end('Response'); var start = new Date().getTime(); eventEmitter.emit('data', true); eventEmitter.emit('error', false); while(new Date().getTime() - start < 5000) { //Let me sleep } process.nextTick(function () { console.log('This is event loop'); }); }).listen(8090); 

Nodejs is single-threaded and runs in eventloop, and the same thread serves events. Thus, in the above code for the request to my localhost: thread 8090 node should be busy serving the request [eat sleep for 5 seconds].

At the same time, eventEmitter events emit two events. Therefore, both of these events must be queued in the eventloop for processing after the request is submitted.

But this does not happen, I see that events are serviced synchronously when they are emitted.

Is this expected? I understand that if it works as I expect, then there will be no use of the event extension module. But how are events emitted by the eventEmitter handler handled?

+4
source share
1 answer

Only objects that require asynchronous processing are placed in the event loop. The standard event emitter in node will send the event immediately. Only code that uses things like process.nextTick , setTimeout , setInterval or code that explicitly adds it to C ++ affects the event loop, such as node libraries.

For example, when you use the node fs library for something like createReadStream , it returns a stream, but opens the file in the background. When it is open, node adds events to the loop, and when the called function in the loop is called, it raises the "open" event in the stream object. Then, the node will load blocks from the file in the background and add the data event trigger in the stream to the event loop.

If you want these events to come out after 5 seconds, you should use setTimeout or put emit calls after a busy cycle.

I would also like to be clear, you should never have such a busy cycle in node code. I can’t say if you are only doing this to check the event loop or if it is part of some real code. If you need more information, please extend the functionality you want to achieve.

+7
source

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


All Articles