EventEmitter class in NodeJS

Alejandro Pascual
4 min readNov 1, 2023

--

In Node.js, EventEmitter is a class in the events module.

This class (EventEmitter) is used to implement the “Emitter” or “Publisher-Subscriber” design pattern, also known as the Observer pattern.

The events module provides a way to work with events and the EventEmitter class is the core of this system. It allows objects to emit events and subscribe to events emitted by other objects. Events are an effective way to handle asynchronous operations in Node.js and are widely used for communication between different parts of an application.

EventEmitter is a class within the events module that provides us with multiple functionalities for working with events, such as event creation, communication channel management, and event emission, among other features.

Basic Event Handling Methods

TheEventEmitter class operates through callback mechanisms and contains two main methods that help us listen to and publish events:
- Listening to events: on.
- Emitting events: emit.

Here is a very simple example:

import EventEmitter from 'node:events';

const myEmitter = new EventEmitter();

// Register a handle for the event 'newPerson'
myEmitter.on('newPerson', () => {
console.log('New person is being registered');
});

// Emit the event 'newPerson'
myEmitter.emit('newPerson');

In this example, EventEmitter is a class used to create an instance called myEmitter , which can emit and handle custom events, in this case, the newPerson event.

Below you can find the same example, but now we have passed an object in the event:

import Event from 'node:events';

const myEmitter = new Event();

// Register a handle for the event 'newPerson'
myEmitter.on('newPerson', ({name, age}) => {
console.log(`New person is being registered. The name is ${name}, and the age is ${age}`);
});

const obj = {name: 'Ale', age: 37};
// Emit the event 'newPerson'
myEmitter.emit('newPerson', obj);

Any object or class we have can be made to extend the EventEmitter class, and thus, utilize all the features it contains (and make use of the Observerpattern).

Here is another example with a class extending from EventEmitter:

import Event from 'node:events';

class Person extends Event.EventEmitter { }
const person = new Person();

person.on('hello', () => {
console.log('Hello world!');
});

person.emit('hello');

IMPORTANT NOTE:

Communication between the parties must be through the same registered class. Listeners that are separated by different instances won’t hear each other.

Here’s an example of two different instances of listening to the same event on different channels:

import Event from 'node:events';

class Person extends Event.EventEmitter { }
class Animal extends Event.EventEmitter { }

const person = new Person();
const animal = new Animal();

person.on('talk', () => {
console.log('Hello world!'); // this printed when person.emit('talk')
});

animal.on('talk', () => {
console.log(`Animal doesn't speak`); // this not printed when person.emit('talk')
});

person.emit('talk');

List of Most Used Methods

The events module is extensive; we are not limited to emitting and listening to events only. We can also add and remove listeners.

Here are the most commonly used methods and their brief descriptions:

  • eventNames: Returns an array of strings for the assigned events.
  • once: Listens for an event that will trigger only once.
  • removeListener: Removes a specific listener.
  • removeAllListeners: Removes all listeners for the event.

Below you can find an example:

import { EventEmitter } from 'node:events';

class EventManager extends EventEmitter {
constructor() {
super();
}

// Method for listening to an event using .on
listenToEvent(event, callback) {
this.on(event, callback);
}

// Method for emitting an event using .emit
triggerEvent(event, data) {
this.emit(event, data);
}
}

// Create a new instance
const eventManager = new EventManager();

// Listening an event using .on
eventManager.listenToEvent('greeting', (message) => {
console.log(`Message received: ${message}`);
});

// Emitting an event using .emit
eventManager.triggerEvent('greeting', 'Hello from the event!');

// Get event names using eventNames
const events = eventManager.eventNames();
console.log('Registered event names:', events);

// Listen for an event that will fire only once using .once
eventManager.once('justOnce', () => {
console.log('This event will only be executed once.');
});

// Broadcast the event once
eventManager.triggerEvent('justOnce');
eventManager.triggerEvent('justOnce'); // This event will not fire

// Remove a specific listener using removeListener
const customListener = (data) => {
console.log('Custom listener:', data);
};

eventManager.listenToEvent('customEvent', customListener);
eventManager.triggerEvent('customEvent', 'First call');
eventManager.removeListener('customEvent', customListener);
eventManager.triggerEvent('customEvent', 'Second call (must be silenced)');

eventManager.listenToEvent('eventToDelete', () => {
console.log('This event will be removed');
});

eventManager.triggerEvent('eventToDelete');
// Remove all listeners from an event using removeAllListeners
eventManager.removeAllListeners('eventToDelete');
eventManager.triggerEvent('eventToDelete'); // This event will not fire

In this example, we create an instance of the EventManager class, which extends EventEmitter. Then, we use various methods:

  • .on: We use listenToEvent to register a listener for the “greeting” event.
  • .emit: We use triggerEvent to emit the “greeting” event with a message.
  • eventNames: We display the names of the registered events.
  • once: We register a listener for the “justOnce” event, which will trigger only once.
  • removeListener: We add and then remove a specific listener.
  • removeAllListeners: We add an event and then remove all registered listeners for that event.

If you want to learn more about events In Node.js, you can click here.

Thank you for reading this article. I hope you liked it and found it useful

Regards!

--

--

Alejandro Pascual

Software Engineer. Software Architect and Technical Lead.