Nodejs Events: What Are They and How Do They Work?

Node Js Events Thumbnail

NodeJS Events provides a way to create custom events that can run asynchronously to perform different operations.

Events in JavaScript

In JavaScript, an event is a way to detect the different types of responses from the users to perform various operations. The functionality of events in JavsScript is defined by the programmers but triggered by the users.

For example, a programmer can set what happens when a user clicks on a button using the onClick event. 

Working With Events in NodeJS

The event in Node.js is quite different, they are created by programmers and are also triggered by programmers in different places to perform the operation defined during the creation of that event.

For example, a programmer defines an event that sends an email, then it is also triggered by the programmers in different places when there is a need to send an email like during the signup, login, forget the password, etc.

Import Event Module

For using the Events in Node.js it is required to import it.

Syntax:

const EventEmitter = require('events');

Create Event Emitter Object

For calling the method, we have to create an Event Emitter object using the below statement.

Syntax:

const EventEmitter = require('events');
const emitter = new EventEmitter();

Methods to Add Lishners to the Events

There are three methods to add listeners to an event.

  1. addListener
  2. on
  3. once

addListener

This method is used to add listeners to an event. We can add multiple listeners to an event. Behind the scene, there is an array attached to a particular event that contains all the listeners associated with that event. And this addListener will add a listener to that array.

Syntax:

addListener(event, listener)

Where the event is the string containing a name that will use to emit the event and the listener is a function that defines the functionality of the event.

on

This method is the same as the addListener method. Provider a shorter form which convenient to use.

Syntax:

on(event, listener)

once

This method is used to attach a single listener to an event that can emit only one time, then it is automatically removed.

Syntax:

once(event, listener)

Remove Listeners

There are several listeners attached to a particular event and to remove them, we have two methods.

  1. removeListener
  2. removeAllListeners

removeListener

This function takes two arguments, the first is the event, and the second is the listener you want to remove from that event.

Syntax:

removeListener(event, listener)

removeAllListeners

This function takes an event as an argument and removes all listeners attached to it.

Syntax:

removeAllListeners(event)

Emit the Event

Emitting the event means calling the event. We can call events anywhere between the programs by using the below method.

emit

This method is used to emit the events. As arguments, it takes an event to emit it, and multiple arguments that will use as arguments for listeners attached to that event.

Syntax: 

emit(event, arguments)

Complete Example of using NodeJS Events

Let’s understand the practical use of every single method we have learned by using a simple example. 

const EventEmitter = require('events');
const emitter = new EventEmitter();

// create listerners

const listener1 = (name) => {
    console.log("Hello " + name);
}

const listener2 = (name) => {
    console.log("Goodbye " + name);
}

const listener3 = (name) => {     
    console.log(name + ", this listener will remove!");
};

// add listerner using addListener method

emitter.addListener("event", listener1);

// add listerner using on method

emitter.on("event", listener2);
emitter.on("event", listener3);

// emit event

emitter.emit("event", "John");

// remove listerner3 using removeListener method

emitter.removeListener("event", listener3);

console.log("------Listner3 removed------");

// emit event

emitter.emit("event", "John");

// remove all listerners using removeAllListeners method

emitter.removeAllListeners("event");

console.log("------All listeners removed!------");

// emit event

emitter.emit("event", "John");

Output:

Output 1

Some more useful methods for NodeJS events

listeners

This method takes an event as an argument and returns an array of listeners for that event.

Syntax:

listeners(event)

setMaxListeners

By default, the EventEmitters will print a warning if more than 10 listeners are attached to a particular event. But by using this method we can increase the number of the max listener.

Syntax:

setMaxListeners(n)

where n is the number of listeners.

Summary

In Node.js custom events can be created, which can be called asynchronous without blocking the execution of other blocks of code. This event contains an array of all listeners attached to it. We can add max 10 listeners to an event, but it can be increased using the setMaxListeners function. We can remove a particular listener from an event or remove all the listeners associated with an event. Hope this article helps you to understand the concept of Events in Node.js.

Reference

https://nodejs.org/api/events.html#events