The EventEmitter class in NodeJS is a core module that provides a way to handle asynchronous events. It allows objects to emit events and other objects to listen and respond to those events.
Event Emitter in Node
NodeJS uses an events module to create and handle custom events. The EventEmitter class can be used to create and handle a custom events module.
Importing EventEmitter
The syntax to Import the events module is given below:
Syntax
const EventEmitter = require('events');
All EventEmitters emit the event newListener when new listeners are added and removeListener when existing listeners are removed. It also provides one more option:
boolean captureRejections
Default Value: false
It automatically captures rejections.
Listening events
Before emits any event, it must register functions(callbacks) to listen to the events.
Syntax
eventEmitter.addListener(event, listener)
eventEmitter.on(event, listener)
eventEmitter.on(event, listener) and eventEmitter.addListener(event, listener) are pretty much similar. It adds the listener at the end of the listener’s array for the specified event. Multiple calls to the same event and listener will add the listener multiple times and correspondingly fire multiple times. Both functions return emitter, so calls can be chained.
Emitting events
In NodeJS, each event is represented by a specific event name. We can trigger an event using the emit(event, [arg1], [arg2], […]) function. Arbitrary arguments can be passed to the listener functions when the event is emitted.
Syntax:
eventEmitter.emit(event, [arg1], [arg2], [...])
Example: This example demonstrates how to create an EventEmitter instance in NodeJS, register a listener for a custom event, and emit that event with a message.
JavaScript
// Importing events
const EventEmitter = require('events');
// Initializing event emitter instances
let eventEmitter = new EventEmitter();
// Registering to myEvent
eventEmitter.on('myEvent', (msg) => {
console.log(msg);
});
// Triggering myEvent
eventEmitter.emit('myEvent', "First event");
Output:
First event
Removing Listener
The eventEmitter.removeListener() takes two argument event and listener, and removes that listener from the listeners array that is subscribed to that event. While eventEmitter.removeAllListeners() removes all the listener from the array which are subscribed to the mentioned event.
Syntax:
eventEmitter.removeListener(event, listener)
eventEmitter.removeAllListeners([event])
Example: This example demonstrates how to register multiple listeners for an event using NodeJS EventEmitter, remove a specific listener, and remove all listeners, showing the flexibility in managing event handling
JavaScript
// Importing events
const EventEmitter = require('events');
// Initializing event emitter instances
let eventEmitter = new EventEmitter();
let geek1= (msg) => {
console.log("Message from geek1: " + msg);
};
let geek2 = (msg) => {
console.log("Message from geek2: " + msg);
};
// Registering geek1 and geek2
eventEmitter.on('myEvent', geek1);
eventEmitter.on('myEvent', geek1);
eventEmitter.on('myEvent', geek2);
// Removing listener geek1 that was
// registered on the line 13
eventEmitter.removeListener('myEvent', geek1);
// Triggering myEvent
eventEmitter.emit('myEvent', "Event occurred");
// Removing all the listeners to myEvent
eventEmitter.removeAllListeners('myEvent');
// Triggering myEvent
eventEmitter.emit('myEvent', "Event occurred");
Output:
Message from geek1: Event occurred
Message from geek2: Event occurred
We registered two times geek1 and one time geek2. For calling eventEmitter.removeListener(‘myEvent’, geek1) one instance of geek1 will be removed. Finally, removing all listener by using removeAllListeners() method that will remove all listeners to myEvent.
Special Events
All EventEmitter instances emit the event ‘newListener’ when new listeners are added and ‘removeListener’ existing listeners are removed.
Event: ‘newListener’ The EventEmitter instance will emit its own ‘newListener’ event before a listener is added to its internal array of listeners. Listeners registered for the ‘newListener’ event will be passed to the event name and reference to the listener being added. The event ‘newListener’ is triggered before adding the listener to the array.
eventEmitter.once( 'newListener', listener)
eventEmitter.on( 'newListener', listener)
Event: ‘removeListener’ The ‘removeListener’ event is emitted after a listener is removed.
eventEmitter.once( ‘removeListener’, listener)
eventEmitter.on( 'removeListener’, listener)
Event: ‘error’ When an error occurs within an EventEmitter instance, the typical action is for an ‘error’ event to be emitted. If an EventEmitter does not have at least one listener registered for the ‘error’ event, and an ‘error’ event is emitted, the error is thrown, a stack trace is printed, and the NodeJS process exits.
eventEmitter.on('error', listener)
Example: This example demonstrates how to handle special events like newListener and removeListener in NodeJS’ EventEmitter, alongside registering and removing custom listeners, and handling errors effectively.
JavaScript
// Importing events
const EventEmitter = require('events');
// Initializing event emitter instances
let eventEmitter = new EventEmitter();
// Register to error
eventEmitter.on('error', (err) => {
console.error('Attention! There was an error');
});
// Register to newListener
eventEmitter.on( 'newListener', (event, listener) => {
console.log(`The listener is added to ${event}`);
});
// Register to removeListener
eventEmitter.on( 'removeListener', (event, listener) => {
console.log(`The listener is removed from ${event}`);
});
// Declaring listener geek1 to myEvent1
let geek1 = (msg) => {
console.log("Message from geek1: " + msg);
};
// Declaring listener geek2 to myEvent2
let geek2 = (msg) => {
console.log("Message from geek2: " + msg);
};
// Listening to myEvent with geek1 and geek2
eventEmitter.on('myEvent', geek1);
eventEmitter.on('myEvent', geek2);
// Removing listener
eventEmitter.off('myEvent', geek1);
// Triggering myEvent
eventEmitter.emit('myEvent', 'Event occurred');
// Triggering error
eventEmitter.emit('error', new Error('Attention!'));
Output:
The listener is added to removeListener
The listener is added to myEvent
The listener is added to myEvent
The listener is removed from myEvent
Message from geek2: Event occurred
Attention! There was an error
Conclusion
The EventEmitter class in NodeJS is essential for building event-driven applications, making it easy to create and manage custom events, handle multiple listeners, and streamline asynchronous tasks.
Similar Reads
EventEmitter Object in Node.js
In Node.js, the EventEmitter object plays a pivotal role in building scalable and asynchronous applications. It allows you to create, emit, and listen for custom events, making it a fundamental building block for managing and coordinating different parts of an application. This article delves into t
5 min read
NodeJS Event Loop
The event loop in Node.js is a mechanism that allows asynchronous tasks to be handled efficiently without blocking the execution of other operations. It: Executes JavaScript synchronously first and then processes asynchronous operations.Delegates heavy tasks like I/O operations, timers, and network
6 min read
Node.js Process exit Event
The process is the global object in Node.js that keeps track of and contains all the information of the particular node.js process that is executing at a particular time on the machine. The process.exit() method is the method that is used to end the Node.js process. Every process action on the mach
2 min read
Node.js Events
An event in NodeJS is an action or occurrence, such as a user click, a file being read, or a message being received, that NodeJS can respond to. Events are managed using the EventEmitter class, which is part of NodeJS's built-in events module. This allows NodeJS to react to various actions asynchron
7 min read
Node.js Process message Event
The 'message' is an event of class Process within the process module which is emitted whenever a message sent by a parent process using childprocess.send() is received by the child process. Syntax: Event: 'message'Parameters: This event does not accept any argument as a parameter. Return Value: This
2 min read
React Events Reference
In React, events handle user actions like clicks, typing, and form submissions. React uses a synthetic event system that makes it easy to manage these events consistently across browsers. This guide will help you understand how React events work and how to use them in your applications. What are Rea
4 min read
Callbacks and Events in NodeJS
Callbacks and events are fundamental building blocks for asynchronous programming in NodeJS. They're essential for handling operations that might take some time, ensuring your application handles asynchronous operations smoothly. Callback in NodeJSIn NodeJS, Callbacks are functions passed as argumen
3 min read
NodeJS Introduction
NodeJS is a runtime environment for executing JavaScript outside the browser, built on the V8 JavaScript engine. It enables server-side development, supports asynchronous, event-driven programming, and efficiently handles scalable network applications. NodeJS is single-threaded, utilizing an event l
5 min read
Firebase Event Types
Firebase provides event types such as value, child_added, onSnapshot, and onAuthStateChanged across its services like Realtime Database, Cloud Firestore, and Authentication. These events allow developers to monitor changes in data and user authentication states, enabling instant updates and interact
4 min read
Node.js emitter.eventNames() Method
In Node.js, most of the core APIs are built near around an idiomatic asynchronous and event-driven architecture. EventEmitter class has instances that are emitted as events by all objects, in which these objects expose an eventEmitter.on() function. It is necessary to import events library (require(
2 min read