Learn about Event Emitters in Node.js

2
5422
Event Emitters

In the last article, we discussed the concept of event driven programming where the Node.js application runs on a single thread but still it achieves concurrency through event and callback functions. Callback is defined as an event which is invoked or called immediately after the completion of a particular task. In this article, we are going to learn about the various events that node emits and the responsible ‘events.EventEmitter’ class along with suitable examples.

Some of the examples of events that objects emit in a Node are as follows.

  • A ‘net.Server’ emits an event when it connects to a peer.
  • An ‘fs.readStream’ emits an event when a file is opened in a particular mode.

In Node.js, this is a rule of thumb that any object that emits an event is always an instance of ‘events.EventEmitter’ class. Let’s discuss in details about the various methods and capacity of events.EventEmitter’ class in detail.

EventEmitter Class
It is present in the “events” module of Node.js. It can be accessed in the following way as explained in the last article.

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

// Create an eventEmitter instance
var eventEmitter = new eventsInstance.EventEmitter();

Explanation of the code: –

  • Firstly, we are importing the required module by using the required directive “events” in order to load the “events” module and storing the returned “events” instance into an eventsInstance variable.
  • Next, we are creating an eventEmitter instance by using ‘eventsInstance.EventEmitter ()’ where the instance is returned into eventEmitter variable as shown above.

Note: – Whenever an EventEmitter instance surfaces any error, then it immediately emits an ‘error’ event.

Class Methods of EventEmitter Class
The following is the summary of class method present in the events.EventEmitter’ class.

S No.

Class Method

Description

1.

listenerCount (emitter, event)

This class method is used to return the number of listeners for a given event.

Types of Events

S No.

Events

Description

1.

newListener

event − String: the event name

listener − Function: the event handler function

The ‘newListener’ event is emitted at the moment when a listener is added. When such an event is triggered, the listener may not be added to the array of listeners for the event at that moment.

2.

removeListener

event − String: the event name

listener − Function: the event handler function

The ‘removeListener’ event is emitted at the moment when a listener is removed. When such an event is triggered, the listener may not be removed from the array of listeners for the event at that moment.

Methods of EventEmitter Class
The following is the summary of methods present in the events.EventEmitter’ class.

S No.

Method

Description

1.

addListener (event, listener)

This method is used to add a listener at the end of the listeners array for the specified event. There are no checks which are made to verify whether the listener has already been added or not. If we pass the same combination of events and listeners through multiple calls then it will add the listener multiple times. It returns emitter, making the chained calls.

2.

on (event, listener)

This method is used to add a listener at the end of the listeners array for the specified event. There are no checks which are made to verify whether the listener has already been added or not. If we pass the same combination of events and listeners through multiple calls, then it will add the listener multiple times. It returns emitter, making the chained calls.

3.

once (event, listener)

This method is used to add a onetime listener to the event. This listener will be invoked only when the next time the event is fired, after which it will be removed immediately. It returns emitter, making the chained calls.

4.

removeListener (event, listener)

This method is used to remove a listener from the listener array for the specified event. It should be used with a caution as It changes the array indices in the listener array behind the listener. Also, the ‘removeListener’ method will remove at most one instance of a listener from the listener array. In the case where, any single listener has been added multiple times to the listener array for the specified event, then we must call ‘removeListener’ multiple times in order to remove each instance. It returns emitter, making the chained calls.

5.

removeAllListeners([event])

This method is used to remove all listeners, or those of the specified event. It is not recommended to remove listeners that were added elsewhere in the code as may disrupt the event driven programming call chain. It returns emitter, making the chained calls.

6.

setMaxListeners (n)

This method is used to set the limit to the addition of the maximum number of listeners (n) to a particular event. Also by default, EventEmitters will print a warning when more than 10 listeners are added for a particular event. It can be useful in detecting memory leaks. Set the value to zero for unlimited.

7.

listeners (event)

This method is used to return an array of listeners for the specified event.

8.

emit (event, [arg1], [arg2], […])

This method is used to execute each of the listeners in order as supplied in the arguments. It returns true if the event had listeners, otherwise returns false.

Demo Example
Lets’ understand the ‘events.EventEmitter’ class methods and events in the best way with the help of the following demo example.

var eventsInstance = require('events');
var eventEmitter = new eventsInstance.EventEmitter();

// Creating listener Function #1
var ListenerFunction1 = function ListenerFunction1() {
   console.log('Execution completed for the Listener no. 1');
};

// Creating listener Function #2
var ListenerFunction2 = function ListenerFunction2() {
  console.log('Execution completed for the Listener no. 2');
};

// Binding the integration event with the ListenerFunction1 function..
eventEmitter.addListener('integration', ListenerFunction1);

// Binding the integration event with the ListenerFunction2 function
eventEmitter.on('integration', ListenerFunction2);

var eventListeners = require('events').EventEmitter.listenerCount
   (eventEmitter,'integration');
console.log(eventListeners + " Listener(s) are listening to the integration event");

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

// Remove the binding for the Listener function 1 
eventEmitter.removeListener('integration', ListenerFunction1);
console.log("Listener function 1 will stop listen now.");

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

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

console.log("Program execution completed successfully...");

Explanation of the code

  • Firstly, we are importing the required module by using the required directive “events” in order to load the “events” module and store the returned “events” instance into an eventsInstance variable as shown above.
  • Next, we are creating an eventEmitter instance by using the ‘eventsInstance.EventEmitter ()’ where the instance is returned into eventEmitter variable as shown above.
  • Then, we will create two event listener functions namely ‘ListenerFunction1’ and ‘ListenerFunction2’.
  • After that, we will bind the integration event with the ‘ListenerFunction1’ and ‘ListenerFunction2’ functions.
  • Next, we will fire the integration event.
  • Then, we will remove the binding for the ‘ListenerFunction1’ and will again fire the integration event.
  • Lastly, we will log a predefined message ‘Program execution completed successfully…’ on to the console.

Output
When we execute the code present in the ‘event-emitter.js’ file by using the node command, we can observe the following output.

C:\odesk\Abhishek Thakur\NodeJS\EventEmitterApplication>node event-emitter.js
2 Listener(s) are listening to the integration event
Execution completed for the Listener no. 1
Execution completed for the Listener no. 2
Listener function 1 will stop listen now.
Execution completed for the Listener no. 2
1 Listener(s) are listening to integration event
Program execution completed successfully...

C:\odesk\Abhishek Thakur\NodeJS\EventEmitterApplication>

EventEmitterApplication

Source code for Event Emitter Application

Conclusion
In this article, we have covered the various events that the node emit and the responsible ‘events.EventEmitter’ class in Node.js along with the suitable examples which are required by a beginner developer to work.

2 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here