Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs event handling

Following 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 it runs in an eventloop and the same thread serves the events. So, in the above code on a request to my localhost:8090 node thread should be kept busy serving the request [there is a sleep for 5s].

At the same time there are two events being emitted by eventEmitter. So, both these events must be queued in the eventloop for processing once the request is served.

But that is not happening, I can see the events being served synchronously as they are emitted.

Is that expected? I understand that if it works as I expect then there would be no use of extending events module. But how are the events emitted by eventEmitter handled?

like image 928
Tamil Avatar asked Feb 21 '23 11:02

Tamil


1 Answers

Only things that require asynchronous processing are pushed into the event loop. The standard event emitter in node will dispatch an event immediately. Only code using things like process.nextTick, setTimeout, setInterval, or code explicitly adding to it in C++ affect the event loop, like node's libraries.

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

If you wanted those events to be emitted after 5 seconds, you'd want to use setTimeout or put the emit calls after your busy loop.

I'd also like to be clear, you should never have a busy loop like that in Node code. I can't tell if you were just doing it to test the event loop, or if it is part of some real code. If you need more info, please you expand on the functionality you are looking to achieve.

like image 94
loganfsmyth Avatar answered Feb 26 '23 20:02

loganfsmyth