×

Node.js Events Module

Introduction to the Node.js events Module

As we’ve already discussed, Node.js is a JavaScript runtime with an event-driven architecture designed to perform Asynchronous tasks. In order to accomplish the event-driven architecture, Node.js relies on the events module. The events module is a built-in module for Node.js and has an EventEmitter object, which emits a named event that causes the execution of the Function objects (“listeners”)

An EventEmitter object has two key functions:

  • The main function of an EventEmitter object is to emit a named event.
  • Another function of an EventEmitter object is to attach or detach one or more event listeners to the named event.

Since the events module is a core module, here’s an illustration for initializing the module.

Firstly, we have to import the events module using the require() function:

const EventEmitter = require(‘events’);

Here, the EventEmitter is a class. Secondly, we have to create a new instance of the EventEmitter class:

const eventEmitter = new events.EventEmitter();

The EventEmitter object is exposed to multiple properties and methods, including on and emit.

  • The on property is used to include a callback function that functions when the event is activated.
  • The emit property is used to activate an event.

Here’s an example is given below to demonstrates the use of these properties:

// Importing the events module
const EventEmitter = require('events');
// Creating a new instance for the EventEmitter class
const emitter = new EventEmitter();
// Creating a callback function for execution
emitter.on('program', () => {
    console.log('This program is running!!');
});
// Activating the event
emitter.emit('program');

The Output of the above program is given as follows:

This program is running!!

Some Methods & Properties of EventEmitter Object

There are numerous methods and properties used in EventEmitter Object. Some of them are listed below:

  • eventNames()
  • addListener()
  • listenerCount()
  • listeners()
  • defaultMaxListener
  • getMaxListener()
  • setMaxListener()
  • prependListener()
  • prependOnceListener()
  • removeListener()
  • removeAllListeners()

eventNames()

The eventNames() method delivers an array that contains all the events for which the listeners have been registered by the emitter.

addListener()

The addListener() method is used to add a specified listener to an event. This method is an alias for on.

listenerCount()

The listenerCount() method returns the number of listener for a specified event 

listeners()

The listeners() method is used to deliver an array containing all the listeners for a specified event.

defaultMaxListener

The defaultMaxListener property is used to set a maximum number of listeners for a specified event. However, only ten listeners can be registered for an event by default.

getMaxListener()

The getMaxListener() method is used to see the maximum number of listeners allowed for an event.

setMaxListener()

The setMaxListener() method is used to modify the maximum number of listeners for a particular event. However, by default, the maximum limit is set to 10.

prependListener()

The prependListener() method is used to add the particular listener as the first event.

prependOnceListener()

The prependOnceListener() method is used to add the particular listener as the first event only for once. However, the listener is removed, when the particular listener has been executed.

removeListener()

The removeListener() method is used to remove the particular listener from an event.

removeAllListener()

The removeAllListener() method is used to remove all the listeners from an event.

Let’s see an example based on the methods described above.

File: events.js

var events = require('events');
var eventEmitter = new events.EventEmitter();
// Initializing the first listener
var myListener = function myListener() {
   console.log('myListener is Initialized.');
}
// Initializing the second listener
var yourListener = function yourListner() {
   console.log('yourListener is Initialized.');
}
// Binding the join event with the myListener function
eventEmitter.addListener('join', myListener);
// Binding the join event with the yourListener function
eventEmitter.on('join', yourListener);
var eventListeners = require('events').EventEmitter.listenerCount
   (eventEmitter,'join');
console.log(eventListeners + "\nThe Listeners are listening to join event");
// Activating the join event 
eventEmitter.emit('join');
// Removing the binding of myListener function
eventEmitter.removeListener('join', myListener);
console.log("myListener is deactivated!!");
// Activating the join event 
eventEmitter.emit('join');
eventListeners = require('events').EventEmitter.listenerCount(eventEmitter,'join');
console.log(eventListeners + "\nThe Listner is listening to join event!");
console.log("Program has been Ended!");

To execute the above program, type the following command on the Node.js command-line:

$ node events.js

The Output of the same should look, as follows:

2
The Listeners are listening to join event
myListener is Initialized.
yourListener is Initialized.
myListener is deactivated!!
yourListener is Initialized.
1
The Listner is listening to join event!
Program has been Ended!

Related Topics

Node.js Event Loop Phases

Node.js – Phases of Event Loop Once we have understood the Node.js event loop concept and the basic introduction to its phases, let's discuss the functions of the Check handler phase...

4 minutes read.

Difference Between Node.js and Django

Node.js vs Django In Web Application Development, we must have a robust technology to provide strength to our Web application. Node.js and Django both are pretty commanding technologies that help us...

6 minutes read.

How to Install Node.js on Windows?

Environment Setup for Node.js Since Node.js is a mandatory section of the program that runs JavaScript, similar to all other required section of programs that run a programming language, it is...

4 minutes read.

Node.js REPL

Node.js REPL: REPL represents the Read Eval Print Loop. REPL is modest; much more, an interactive software development environment similar to the command line shells used in various Operating Systems....

4 minutes read.

Node.js NPM

Node.js – Node Package Manager NPM is an abbreviation for Node Package Manager. It is the default package manager developed by Isaac Z. Schlueter using JavaScript Programming Language, designed for JavaScript Runtime...

7 minutes read.

Node.js HTTP Module

An Introduction to HTTP Module The http module is a core module in Node.js that uses the Hypertext Transfer Protocol (HTTP) to transfer data. With the help of the http module,...

7 minutes read.

Node.js OS Module

Introduction to Node.js OS Module The OS Module in Node.js provides the Operating System-related Utilities. This module delivers the functions to interact with the Operating System. It also delivers the Operating...

5 minutes read.

Node.js Console

Node.js Console: Like the JavaScript console mechanism, a console module is designed for Node.js that provides a debugging console for writing or printing messages. Usually, in JavaScript, a console mechanism is...

4 minutes read.

Node.js Streams

An Introduction to the Streams Streams are one of the elemental concepts that are introduced to power the applications based on Node.js. These are the method used to handle the data...

6 minutes read.

Differentiation of Web Scraping and Web Crawling

Most of us get confused between the word’s web scraping and web crawling, and even some people think they are synonyms for each other. But there is a considerable difference between...

3 minutes read.

Node.js Events Module

Introduction to the Node.js events Module As we’ve already discussed, Node.js is a JavaScript runtime with an event-driven architecture designed to perform Asynchronous tasks. In order to accomplish the event-driven architecture,...

4 minutes read.

Difference Between Nodejs Angular and React

A Right JavaScript Framework Within a business, it is necessary to pick the right technology. As much as this applies to the web application and software development, it also applies in...

5 minutes read.

Node.js Parsing Arguments

Understanding Command-Line Arguments The Strings of text used to transfer extra information to a program through the command-line interface (CLI) while execution of the application, is known as Command-Line arguments. These...

9 minutes read.

Node.js Event Loop

An Introduction to Event Loop As we have already discussed, Node.js is an Asynchronous platform with a non-blocking I/O. Node.js has awesome features that made it this thriving, and the Event...

5 minutes read.

Node.js Error Handling

Node.js – Error Handling: Errors are part of every programming language, and Node.js Environment is not an exception. There are many predefined errors in Node.js, including errors like SyntaxError, RangeError, and...

4 minutes read.

Node.js File System

Introduction to File System in Node.js FS, abbreviated as File System, is a Node.js Build-in Module, which provides an Application Programming Interface (API) to interact with the File System, and to...

15 minutes read.

Node.js Path Module

Understanding the path Module in Node.js The path module is a built-in module of Node.js that provides various methods to interact with the files and directory path names on the device’s...

6 minutes read.

Node.js Discovering Timers

Node.js Discovering Timers: Timers are multi-lingual, and much functional in countless use cases. The Timers are mostly used in many popular programming languages, including Node.js. However, it's pretty simple to...

4 minutes read.

Difference Between Node.js and PHP

Node.js vs PHP Node.js and PHP both are the powerful back-ends to create versatile websites. Even when these two technologies fall under the same category, their features are pretty diverse. There's...

6 minutes read.

Node.js Core Debugger

Node.js – Core Debugger: It’s always a challenge when it comes to debug an application. The Asynchronous workflows of Node.js include an additional layer of intricacy to this difficult process....

3 minutes read.