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)