Node.js – EventEmitter

EventEmitter in Node

As you know from Tutorial 6(Event Loop), Node.js is an event-driven program. Therefore, actions emit events.

For example:

  • when a file if opened
  • when a connection is made
  • when a file is closed

In Node.js, objects can fire events. For example the readStream object can fire events when opening or closing a file.

This is shown below

var fs = require("fs");
path = "D:/nodefiles/testinput.txt"
var readStream = fs.createReadStream(path);
readStream.on("open", function(){
    console.log("A file has been opened");
});

 

Objects that emit events are instances of the events.EventEmitter class. Let’s now talk about EventEmitter.

 

The EventEmitter Class

The EventEmitter class is defined in the events module. So to use it, you need to require the events module. In this way, you can create your own EventEmitter objects. The code below creates a new eventEmitter object.

//import the events module
var events = require("events");

//create an EventEmitter object
var eventEmitter = new events.eventEmitter();

 

An EventEmitter provides a number of properties like the emit and on.

  • the on property binds the event to the handler
  • the emit property is used to fire the event

 

EventEmitter Methods

The table below provide a list of methods for an events.

SN. Method & Brief Description
1 addListener(event, listener)

Adds a listener to the listeners array for the given event. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of event and listener will result in the listener being added multiple times. It returns emitter, hence calls can be chained.

2 on(event, listener)

Adds a listener at the end of the listeners array for the given event. It doesn’t check if the listener has already been added. Multiple calls passing the same combination of event and listener will mean that the  listener can be added multiple times. Emitter is returned, therefore calls can be chained.

3 once(event, listener)

Adds a one time listener to the event. This listener is invoked only the next time the event is fired, after which it is removed. Returns emitter, so calls can be chained.

4 removeListener(event, listener)

Removes a listener from the listener array for the specified event. Caution − It changes the array indices in the listener array behind the listener. removeListener will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified event, then removeListener must be called multiple times to remove each instance. Returns emitter, hence calls can be chained.

5 removeAllListeners([event])

Removes all the listeners, or those of the given event. It’s not a good idea to remove listeners that were added elsewhere in the code, especially when it’s on an emitter you didn’t create (e.g. sockets or file streams). Returns emitter, hence calls can be chained.

6 setMaxListeners(n)

EventEmitters, by default will print a warning if more than 10 listeners are added for a particular event. This is useful because helps finding memory leaks. Granted. not all Emitters should be limited to only 10 listeners. This function makes it possible for that to be increased. To be unlimited, then set it to zero.

7 listeners(event)

Returns an array of listeners for the specified event.

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

This method executes each of the listeners in order with the supplied arguments. It returns true if the event had listeners, else it returns false.

 

Class Methods

One class method in the EventEmitter class is given below:

SN. Method brief  description
1 listenerCount(emitter, event)

This method returns the number of listeners for a specified event.

 

Events

Some events provided by the EventEmitter class are given below

SNo. Events and brief description
1 newListener

  • event − String: the name of the event
  • listener − Function: this is the event-handler function

Any time a listener is added, this event is emitted. However, when it is triggered, the listener may not yet have been added to the array of listeners for the event.

2 removeListener

  • event − String The name of the event
  • listener − Function The event-handler function

This event is emitted any time a listener is removed. However, when it is triggered, the listener may not yet have been removed from the array of listeners for the event.

 

An Example

The code below illustrates how EventEmitters work.

//Program to illustrate EventEmitter
var events = require('events');
var eventEmitter = new events.EventEmitter();

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

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

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

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

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 listner_1 function
eventEmitter.removeListener('connection', listner_1);
console.log("Listner_1 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.");

The output of the code is given below

Event Emitter Listener Output

Event Emitter Listener Output