Node.js - Event Emitter

Node.js

In this tutorial we will learn about Event Emitter of the Node.js events module.

Events

The core APIs of Node.js is based on asynchronous and event driven architecture. So, there are objects that emit events periodically and there are listeners listening to those emitted events.

EventEmitter

The EventEmitter class is part of the events module. It has multiple properties like on, emit etc. We will explore them in this tutorial as we move along.

We use the EventEmitter class to create and handle custom events.

In the following example we are creating object of EventEmitter class.

const events = require('events');
const EventEmitter = events.EventEmitter;

const eventEmitter = new EventEmitter();

We can make it compact like the following.

const EventEmitter = require('events').EventEmitter;

const eventEmitter = new EventEmitter();

The on method

The on method is used to create event listener. It takes the name of the event and a listener callback function. When the event is raised the callback function is called.

Syntax:

emitter.on(eventName, listener)

This adds the listener function to the end of the listeners array for the event named eventName. No checks are made to see if the listener has already been added.

In the following example we are creating an event listener for our custom event by the name CustomEvent. Whenever this custom event is emitted the callback listener function is executed.

const EventEmitter = require('events').EventEmitter;

const eventEmitter = new EventEmitter();

eventEmitter.on('CustomEvent', () => {
    console.log('CustomEvent was fired!');
});

Now we have to emit the CustomEvent using emit method.

The emit method

To emit custom event we use the emit method. The first parameter of the method is the event name followed by arguments.

Syntax:

emitter.emit(eventName[, ...args])

The arguments is optional.

This will synchronously call each listeners registered for the event named eventName, in the order they were registered and it will pass the supplied argument to each of them.

In the following example we are emitting event named CustomEvent.

const EventEmitter = require('events').EventEmitter;

const eventEmitter = new EventEmitter();

eventEmitter.on('CustomEvent', () => {
    console.log('CustomEvent was fired!');
});

eventEmitter.emit('CustomEvent');

Output

CustomEvent was fired!

In the above code we are creating an event listener using on method. The callback function of this event handler is executed when the custom event CustomEvent is emitted.

Next, we are emitting the custom event CustomEvent using the emit method. The emitted event is handled by the listener function which results in the output of the above message in the console.

If we emit the event multiple times we will get the console log that many times.

In the following example we are emitting custom event 3 times. We will get console log thrice.

const EventEmitter = require('events').EventEmitter;

const eventEmitter = new EventEmitter();

eventEmitter.on('CustomEvent', () => {
    console.log('CustomEvent was fired!');
});

eventEmitter.emit('CustomEvent');
eventEmitter.emit('CustomEvent');
eventEmitter.emit('CustomEvent');

Output

CustomEvent was fired!
CustomEvent was fired!
CustomEvent was fired!

Emit event with arguments

In the following example we are going to emit event with some arguments.

const EventEmitter = require('events').EventEmitter;
const eventEmitter = new EventEmitter();

console.log('Creating listener that can take argument...');
eventEmitter.on('GreetingsEvent', message => {
    console.log(message);
});

console.log('Emitting event...');
eventEmitter.emit('GreetingsEvent', 'Hello World!');
eventEmitter.emit('GreetingsEvent', 'One Two Three');
eventEmitter.emit('GreetingsEvent', 'Foo Bar FooBar');

Output

Creating listener that can take argument...
Emitting event...
Hello World!
One Two Three
Foo Bar FooBar

The once method

We use the once method to create a listener that will listen for the event only once.

Syntax:

emitter.once(eventName[, ...args])

In the following example we are creating a listener that will listen only once.

const EventEmitter = require('events').EventEmitter;

const eventEmitter = new EventEmitter();

eventEmitter.once('CustomEvent', () => {
    console.log('CustomEvent was fired!');
});

eventEmitter.emit('CustomEvent');
eventEmitter.emit('CustomEvent');
eventEmitter.emit('CustomEvent');

Even though we are emitting the event thrice but the listener will process it only once.

The listeners method

This will return an array of listeners for the specified event.

In the following example we will get the array of listeners for the event HelloEvent and directly call them.

const EventEmitter = require('events').EventEmitter;

const eventEmitter = new EventEmitter();

eventEmitter.on('HelloEvent', () => {
    console.log('Listener 1');
});
eventEmitter.on('HelloEvent', () => {
    console.log('Listener 2');
});
eventEmitter.on('HelloEvent', () => {
    console.log('Listener 3');
});

// get the listeners for the event HelloEvent
const listeners = eventEmitter.listeners('HelloEvent');

console.log('Calling the listeners:');
listeners.forEach(listener => listener());

Output

Calling the listeners:
Listener 1
Listener 2
Listener 3

The setMaxListeners method

We use this to set the maximum number of listeners for a given event.

By default EventEmitter will print warning if more than 10 listeners are added for a particular event.

We can increase or decrease this limit using the setMaxListeners method.

If we want unlimited listeners then we set the value to 0.

The removeAllListeners method

This method helps in removing all the listeners, or of a specified event.

Syntax:

emitter.removeAllListeners([eventName])

If eventName is not specified then all listeners are removed.

In the following example we will create a listener of event HelloWorldEvent. We will emit event and the listener callback function will be executed. Then we will remove the listener.

const EventEmitter = require('events').EventEmitter;
const eventEmitter = new EventEmitter();

console.log('Creating listener...');
eventEmitter.on('HelloWorldEvent', () => {
    console.log('HelloWorldEvent called.');
});

console.log('Emitting event...');
eventEmitter.emit('HelloWorldEvent');
eventEmitter.emit('HelloWorldEvent');
eventEmitter.emit('HelloWorldEvent');

console.log('Removing listener...');
eventEmitter.removeAllListeners('HelloWorldEvent');

console.log('Emitting event again... This time there is no listener.');
eventEmitter.emit('HelloWorldEvent');

Output:

Creating listener...
Emitting event...
HelloWorldEvent called.
HelloWorldEvent called.
HelloWorldEvent called.
Removing listener...
Emitting event again... This time there is no listener.

Since we removed the listener hence the last emitted event will not be handled.

Alright, this brings us to the end of this tutorial. Thanks for reading. Don't forget to practice. Have fun learning and I will see you again in the next tutorial. Bye :)

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT