EventEmitter Object in Node.js
Last Updated :
24 Jun, 2024
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 the workings of EventEmitter
, exploring its features, common use cases, and best practices for effective event-driven programming in Node.js.
What is an EventEmitter?
EventEmitter
is a class in the events
module of Node.js that provides a way to handle asynchronous events. It is based on the publish-subscribe pattern, where event listeners subscribe to events and respond when those events are published.
Key Concepts
- Event: A named signal emitted by an
EventEmitter
to which listeners can subscribe. - Listener: A function that is invoked in response to a specific event.
Event handling
is quite similar to the callback function, but the callback function is used when asynchronous functions return their result and event handling works on the observer pattern. In NodeJs the functions that listeners the events are called observers. When an event occurs listeners' functions start their execution. There are multiple in-built events available in NodeJs like EventEmitter class. We will show how we can use EventEmitter class in event handling.Â
Features of EventEmitter
Adding Listeners
You can add listeners to an EventEmitter
instance using the on
or addListener
methods. Both methods are synonymous and allow you to attach a callback function to a specified event.
myEmitter.on('event', () => {
console.log('An event occurred!');
});
Emitting Events
To trigger an event, use the emit
method, passing the event name and optional arguments to the listeners.
myEmitter.emit('event');
Removing Listeners
You can remove listeners using the removeListener
or off
methods, or remove all listeners for a specific event using the removeAllListeners
method.
const listener = () => console.log('Another event occurred!');
myEmitter.on('event', listener);
// Remove a specific listener
myEmitter.removeListener('event', listener);
// Remove all listeners for the event
myEmitter.removeAllListeners('event');
Handling One-Time Events
The once
method allows you to add a listener that will be called at most once for a specific event.
myEmitter.once('event', () => {
console.log('This will only be logged once');
});
myEmitter.emit('event'); // Will trigger the listener
myEmitter.emit('event'); // Will not trigger the listener
Event Arguments
You can pass multiple arguments to the listener functions when emitting an event.
myEmitter.on('event', (arg1, arg2) => {
console.log(`Arguments: ${arg1}, ${arg2}`);
});
myEmitter.emit('event', 'arg1', 'arg2');
Creating EventEmitter object
We can use EventEmitter by creating its object and then using it for fire events. We will syntax for EventEmitter object creation. Before creating the EventEmitter object you should import the event.
Step 1: Import events module.
const events = require('events');
Step 2: Creates an EventEmitter object.
const eventEmitter = new events.EventEmitter();
Step 3: Then bind the event and event handler together
eventEmitter.on('eventName', eventHandler);
Step 4: We can fire the event by using emit method
eventEmitter.emit('eventName');
Example 1: In this example, we show how to create an EventEmitter object and then fire an event by using emit() method, and bind the connection used on() of EventEmitter. When execution is stopped we fire connections by using emit().
JavaScript
// index.js
// Import events module
const events = require('events');
// Create an eventEmitter object
let eventEmitter = new events.EventEmitter()
// Create an event handler as follows
let connectHandler = function connected() {
console.log('connection successful.');
// Fire the data_received event
eventEmitter.emit('data_received');
}
// Bind the connection event with the handler
eventEmitter.on('connection', connectHandler);
// Bind the data_received event with the anonymous function
eventEmitter.on('data_received', function () {
console.log('data received successfully.');
});
// Fire the connection event
eventEmitter.emit('connection');
console.log("Program Ended.");
Step to run the application: Run the below command to execute script.js
node index.js
Output:
Example of EventEmitter object Extending EventEmitter class
The EventEmitter class supports inheritance. Sometimes you need to implement a subclass of EventEmitter.
Example 2: In this example, MyEmitter inherits the EventEmitter class. MyEmitter uses the on() method to listen to events. This event is fire using emit().
JavaScript
// index.js
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {
foo() {
this.emit('test');
}
}
let myEmitter = new MyEmitter();
myEmitter.on('test', () => console.log('Yay, it works!'));
myEmitter.foo();
Step to run the application: Run the below command to execute script.js
node index.js
Output:
Example of Extending EventEmitter class Implementation of EventEmitter Methods
Example: In this example, we see the practical implementation of EventEmitter Methods. We see all four methods like on(), emit(), once(), and removeListener() of EventEmitter.
JavaScript
// index.js
const events = require('events');
const eventEmitter = new events.EventEmitter();
// listener #1
let listener1 = function listener1() {
console.log('listener1 executed.');
}
// listener #2
let listener2 = function listener2() {
console.log('listener2 executed.');
}
// Bind the connection event with the listener1 function
eventEmitter.addListener('connection', listener1);
// Bind the connection event with the listener2 function
eventEmitter.on('connection', listener2);
let eventListeners = require('events').EventEmitter.listenerCount
(eventEmitter, 'connection');
console.log(eventListeners + " Listener(s) listening to connection event");
// Fire the connection event
eventEmitter.emit('connection');
// Remove the binding of listener1 function
eventEmitter.removeListener('connection', listener1);
console.log("Listener1 will not listen now.");
// Fire the connection event
eventEmitter.emit('connection');
eventListeners = require('events').EventEmitter.listenerCount
(eventEmitter, 'connection');
console.log(eventListeners + " Listener(s) listening to connection event");
console.log("Program Ended.");
Output:
EventEmitter Methods Features of EventEmitter class
- This class is for handling events.
- It can inherit event functionality in other classes.
- It emits events.
- It listens to and handles events.
- It helps to run multiple threads in the background.
EventEmitter Methods
- emitobj.on(event, listener)
- emitobj.emit(event,[arg1],[arg2],..[argN])
- emitobj.once(event, listener)
- emitobj.removeListener(event, listener)
Similar Reads
NodeJS EventEmitter
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 NodeNodeJS uses an events module to create and handle custom events. The EventEmitter class c
5 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
Explain the Process Object in Node.js
In this article, we are going to explore about process object of Node.js in detail. The Process object in node.js is a global object that can be used in any module without requiring it in the environment. This object is useful in the perspective of getting the information related to the node.js envi
3 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 beforeExit Event
The 'beforeExit' is an event of class Process within the process module which is emitted when Node.js empties its event loop and has no additional work to schedule. Syntax: Event: 'beforeExit'Parameters: This event does not accept any argument as the parameter. Return Value: This event returns nothi
2 min read
Essence of Node.js
Node.js or Node has a small core group of modules, commonly referred to as the Node Core that is exposed as the public Node API by using we write our applications or we can say that the Node Core implements the public Node API. Some examples of the modules present in the node core are: To work with
8 min read
Node.js Writable Stream finish Event
The 'finish' event in a Writable Stream is emitted after the Calling of writable.end() method when all the data is being flushed to the hidden system. Syntax: Event: 'finish' Return Value: If the writable.end() method is being called before then this event is emitted else its not emitted. Below exam
2 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
Node.js Projects
Node.js is one of the most popular JavaScript runtime environments widely used in the software industry for projects in different domains like web applications, real-time chat applications, RESTful APIs, microservices, and more due to its high performance, scalability, non-blocking I/O, and many oth
9 min read
Non-Blocking event loop in Node.js
Node.js operates on a single-threaded, event-driven architecture that relies heavily on non-blocking I/O operations to handle concurrent requests efficiently. This approach is enabled by its event loop mechanism, which allows Node.js to handle multiple requests concurrently without creating addition
5 min read