Event Emitters In Node.JS

03 / Jan / 2014 by Sakshi Tyagi 0 comments

Event Emitters are used to create and manage our own events and trigger them accordingly. We can bind listeners and emit those events whenever required.

Example :

var events = require(‘events’);
var eventEmitter = new events.EventEmitter();
eventEmitter.on(‘Morning’, function welcomeMessage()
console.log(‘Good Morning!!’);

eventEmitter.on(‘Evening’, function goodByeMessage()
console.log(‘Good Evening!!’);

if(new Date().getHours() <= 12)


Here we have created an instance of EventEmitter class,provided by Events module. We have bound two events “Morning” and “Evening”.If the current hours returned is greater than or equal to 12 , event “Morning” is emitted otherwise event “Evening” is emitted.

We can bind more than one function to a single event.

NOTE: If you want create more than 10 listeners on a single event, you will have to make a call to eventEmitter.setMaxListeners(n) where n is the max numbers of listeners (with zero being unlimited number of listeners). This is used to make sure you aren’t accidentally leaking event listeners.

So in this way we can create events, bind listeners to them and trigger them using event emitters.


Leave a Reply

Your email address will not be published. Required fields are marked *