Event Emitter in Node JS

Nodes in Node JS emit many events regularly with the help of event emitter. For instance, whenever a peer user connects with net.Server, it emits an event. Similarly, fs.readStream emits an event upon file opening.

All the event emitting objects are instances of events.EventEmitter. In the previous articles, we are learning about callbacks and events. In continuation of those tutorials, we will see how the event emitter in Node JS class works behind Node JS.

What is EventEmitter class in Node JS?

We have an Event module in Node JS that contains the eventEmitter class. To access the event emitter, see the code below.

// Import events module
var events = require('events');

// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();
  • Error event fires when any event throws and error.
  • newListner event fires when a new event listner adds or registered.
  • removeListner event fires when an event listner removes.

EventEmitter class in Node JS provides various properties

  • on property bind a function with the event.
  • emit property fire an event.

We have gathered some important and most useful methods of the EventEmitter class. Let’s go through the description of these functions and what functionality they provide.

MethodDescription
addListener(event, listener) This method adds a listener to the event at the end of the listener’s array regardless of any checks like multiple entries of the same listener for the event. Passing the same combination of events. listener more than once results in multiple listeners added.
It returns the emitter which can be used in the chaining process.
on(event, listener)Adds a listener to the event at the end of the listener’s array regardless of any checks like multiple entries of the same listener for the event. Passing the same combination of events. listener more than once results in multiple listeners added.
It returns the emitter which can be used in the chaining process.
once(event, listener)This function also adds one listener to the event. The important thing to remember about this function is that the listener added to the event by this function only executes for one time that is after adding it.
It returns the emitter which helps in the chaining of calls.
removeListener(event, listener)removeListener function removes the listener from the listener’s array of an event. It returns the emitter which can be used in calls chaining.
The important thing here is that this function changes the indices of the listeners present in the listener’s array upon the removal of a listener. So, if there is more than one entry of the same listener in the array, this function must be called more than once for that event.
removeAllListeners([event])Removes all the listeners of an event. It is not a good practice to remove the listeners that were created at any other place within the code, especially the listeners which are not created by you like file streams and sockets.
It returns the emitter which can be used to chain the calls.
setMaxListeners(n)For making the debugging process easy and identifying the possible memory leaks, the default limit for the number of maximum listeners for an event is set to 10. There can be some scenarios where it is required to exceed the limit and register more than 10 listeners. In this case, you can use this function and supply the number of listeners you want to create.
Note: Passing 0 will set the limit to unlimited.
listeners(event)If you want to get the listeners registered for a specific event in Node JS, this function return list of all the events against that event.
emit(event, [arg1], [arg2]…)This function receives the event as its first parameter and array of arguments. It returns true if the event had listeners and false in another case.
Methods in EventEmitter class
MethodDescription
listenerCount(emitter, event)This method returns the number of listeners for an event.
EventDescription
newListener– event: Name of the event in string format.
– Listener: the function that handles events.
This event occurs whenever a new listener is added to the listener’s array.
removeListenerThis event is emitted whenever the listener is removed from the listener’s array.
var events = require('events');
var eventEmitter = new events.EventEmitter();

// listener #1
var listner1 = function listner1() {
   console.log('listner1 executed.');
}

// listener #2
var listner2 = function listner2() {
   console.log('listner2 executed.');
}

// Bind the connection event with the listner1 function
eventEmitter.addListener('connection', listner1);

// Bind the connection event with the listner2 function
eventEmitter.on('connection', listner2);

var eventListeners = require('events').EventEmitter.listenerCount
   (eventEmitter,'connection');
console.log(eventListeners + " Listner(s) listening to connection event");

// Fire the connection event 
eventEmitter.emit('connection');

// Remove the binding of listner1 function
eventEmitter.removeListener('connection', listner1);
console.log("Listner1 will not listen now.");

// Fire the connection event 
eventEmitter.emit('connection');

eventListeners = require('events').EventEmitter.listenerCount(eventEmitter,'connection');
console.log(eventListeners + " Listner(s) listening to connection event");

console.log("Program Ended.");

Run the above example with the following command in the terminal.

$ node main.js

The output of the above example should be like the following.

2 Listner(s) listening to connection event
listner1 executed.
listner2 executed.
Listner1 will not listen now.
listner2 executed.
1 Listner(s) listening to connection event
Program Ended.

Reference to the official documentation of Events in Node JS

Scroll to Top