• Node.js Video Tutorials

Node.js - Event Emitter



The Node.js API is based on an event-driven architecture. It includes the events module, which provides the capability to create and handle custom events. The event module contains EventEmitter class. The EventEmitter object emits named events. Such events call the listener functions. The Event Emitters have a very crucial role the Node.js ecosystem. Many objects in a Node emit events, for example, a net.Server object emits an event each time a peer connects to it, or a connection is closed. The fs.readStream object emits an event when the file is opened, closed, a read/write operation is performed. All objects which emit events are the instances of events.EventEmitter.

Since the EvenEmitter class is defined in events module, we must include in the code with require statement.

var events = require('events');

To emit an event, we should declare an object of EventEmitter class.

var eventEmitter = new events.EventEmitter();

When an EventEmitter instance faces any error, it emits an 'error' event. When a new listener is added, 'newListener' event is fired and when a listener is removed, 'removeListener' event is fired.

Sr.No. Events & Description
1

newListener(event, listener)

  • event − String: the event name

  • listener − Function: the event handler function

This event is emitted any time a listener is added. When this event is triggered, the listener may not yet have been added to the array of listeners for the event.

2

removeListener(event, listener)

  • event − String The event name

  • listener − Function The event handler function

This event is emitted any time someone removes a listener. When this event is triggered, the listener may not yet have been removed from the array of listeners for the event.

Following instance methods are defined in EventEmitter class −

Sr.No. Events & Description
1

addListener(event, listener)

Adds a listener at the end of the listeners array for the specified event. Returns emitter, so calls can be chained.

2

on(event, listener)

Adds a listener at the end of the listeners array for the specified event. Same as addListener.

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

4

removeListener(event, listener)

Removes a listener from the listener array for the specified event. 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.

5

removeAllListeners([event])

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

6

setMaxListeners(n)

By default, EventEmitters will print a warning if more than 10 listeners are added for a particular event. Set to zero for unlimited.

7

listeners(event)

Returns an array of listeners for the specified event.

8

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

Execute each of the listeners in order with the supplied arguments. Returns true if the event had listeners, false otherwise.

9

off(event, listener)

Alias for removeListener

Example

Let us define two listener functions as below −

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.');
}

Let us bind these listeners to a connection event. The first function listener1 is registered with addListener() method, while we use on() method to bind listener2.

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

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

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

When the connection event is fired with emit() method, the console shows the log message in the listeners as above

listner1 executed.
listner2 executed.

Let us remove the listener2 callback from the connection event, and fire the connection event again.

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

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

The console now shows the following log −

listner1 executed.
listner2 executed.
Listner1 will not listen now.
listner2 executed.

The EventEmitter class also has a listCount() method. It is a class method, that returns the number of listeners for a given event.

const events = require('events');

const myEmitter = 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
myEmitter.addListener('connection', listner1);

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

// Fire the connection event 
myEmitter.emit('connection');
console.log("Number of Listeners:" + myEmitter.listenerCount('connection'));

Output

listner1 executed.
listner2 executed.
Number of Listeners:2
Advertisements