Search code examples
node.jseventemitter

Events & Event Emitter in Node.js


So I've attached two events if someone screams, they are called synchronously, why so?

const events = require('events'); 

const eventEmitter = new events.EventEmitter();

eventEmitter.on('scream', function() {
    console.log("Screaming");
});

eventEmitter.on('scream', function(name) {
    console.log(name+" is screaming");
});

eventEmitter.emit('scream', 'Bob');

O/P: Screaming

Bob is screaming


Solution

  • Because in nodejs, The event loop is single threaded and pick one event at a time and treat those events independently.

    In your case, there are two event handler with the same name, so when event loop gets the eventEmitter.emit('scream', 'Bob') it sends the particular event handler. When first event handler done with it, Now it goes to the second handler because with the same name. It follow the FIFO but if you use emitter.prependListener(eventName, listener) then it will be executed first the FIFO.

    You should know, if you want to call only one time then you should use eventEmitter.once('scream') It will be called only one time.

    eventEmitter.once('scream', function() {
        console.log("Screaming");
    });
    
    eventEmitter.emit('scream', 'Bob');
    eventEmitter.emit('scream', 'Bob');
    eventEmitter.emit('scream', 'Bob');
    

    Output: Screaming // Only one time.