Paramclasses Academy - Blog

Tutorials Details

←
Post 11 of 40
→

Node.js Events Module: EventEmitter Explained with Examples

Node.js Events Module: EventEmitter Explained with Examples

October 29, 2026

✦ Node.js Events Module: EventEmitter Explained with Examples

Node.js is widely used to build web servers, REST APIs, real-time applications, and backend systems. One important feature that makes Node.js flexible is its event-driven architecture. Events allow different parts of an application to communicate when something happens.

For example, an application might generate an event when a user registers, an order is placed, a file finishes processing, or a payment is completed.

Node.js provides a built-in Events module that includes EventEmitter, a class used to create, listen for, and handle custom events.

In this practical tutorial by Param Classes, you will learn how the Node.js Events module works, how to create custom events, register listeners, pass data to event handlers, and build a practical example.

✦ What Is the Events Module in Node.js?

The Events module is a built-in Node.js module that helps developers implement event-driven programming.

An event represents something that has happened. An event listener is a function that runs when the corresponding event is emitted.

For example:

  • A student registers for a course.

  • A customer places an order.

  • A file upload finishes.

  • A notification needs to be sent.

  • An application records an activity.

You can use events to separate the code that detects an action from the code that responds to it.

Import the module using CommonJS:

const EventEmitter = require('node:events');

Create an instance:

const eventEmitter = new EventEmitter();

You can now register listeners and emit custom events.

✦ What Is EventEmitter?

EventEmitter is a class provided by the Node.js Events module. It allows an object to emit named events and call registered listener functions.

Three important operations are:

  • on() — register a listener.

  • emit() — trigger an event.

  • off() — remove a listener.

Let's look at a basic example.

const EventEmitter = require('node:events');

const eventEmitter = new EventEmitter();

eventEmitter.on('greet', () => {
    console.log('Welcome to Param Classes!');
});

eventEmitter.emit('greet');

Output:

Welcome to Param Classes!

In this example, on() registers a listener for the greet event. The emit() method triggers that event, causing the listener to execute.

✦ Step 1: Create Your First EventEmitter Application

First, check that Node.js is installed:

node -v

Create a project folder:

mkdir node-events-demo
cd node-events-demo
npm init -y

Create a file named app.js.

Your project structure will look like this:

node-events-demo/
├── app.js
└── package.json

You do not need to install an additional npm package because the Events module is built into Node.js.

Add this code to app.js:

const EventEmitter = require('node:events');

const eventEmitter = new EventEmitter();

eventEmitter.on('message', () => {
    console.log('A message event has occurred!');
});

eventEmitter.emit('message');

Run the program:

node app.js

Output:

A message event has occurred!

Congratulations! You have created and triggered your first custom event in Node.js.

✦ Step 2: Pass Data Through an Event

Events become more useful when you pass information to their listeners.

For example, suppose a student registers for a programming course. You can emit an event containing the student's name and course.

const EventEmitter = require('node:events');

const eventEmitter = new EventEmitter();

eventEmitter.on('studentRegistered', (studentName, course) => {
    console.log(`Student Name: ${studentName}`);
    console.log(`Course: ${course}`);
});

eventEmitter.emit(
    'studentRegistered',
    'Rahul',
    'Node.js'
);

Output:

Student Name: Rahul
Course: Node.js

The values passed to emit() are received by the listener function in the same order.

This technique is useful when you want different parts of an application to respond to the same action.

✦ Step 3: Register Multiple Listeners

You can register more than one listener for the same event.

For example, when a new student registers, you might want to display a confirmation and record an activity.

const EventEmitter = require('node:events');

const eventEmitter = new EventEmitter();

eventEmitter.on('studentRegistered', (name) => {
    console.log(`Welcome, ${name}!`);
});

eventEmitter.on('studentRegistered', (name) => {
    console.log(`Registration recorded for ${name}.`);
});

eventEmitter.emit('studentRegistered', 'Amit');

Output:

Welcome, Amit!
Registration recorded for Amit.

Both listeners are called when the event is emitted.

By default, listeners for a particular event are called synchronously in their registration order. If a listener starts asynchronous work, that work may finish later.

✦ Step 4: Use once() for a One-Time Event

Sometimes you want a listener to run only once.

The once() method registers a listener that is automatically removed after its first invocation.

const EventEmitter = require('node:events');

const eventEmitter = new EventEmitter();

eventEmitter.once('welcome', () => {
    console.log('Welcome message displayed once.');
});

eventEmitter.emit('welcome');
eventEmitter.emit('welcome');

Output:

Welcome message displayed once.

Although the event is emitted twice, the listener runs only during the first emission.

This is useful for one-time initialization tasks or actions that should only respond to the first occurrence of an event.

✦ Step 5: Remove an Event Listener

You can remove a previously registered listener using off() or removeListener().

The listener function must be the same function reference that was registered.

const EventEmitter = require('node:events');

const eventEmitter = new EventEmitter();

function showMessage() {
    console.log('Event listener executed.');
}

eventEmitter.on('message', showMessage);

eventEmitter.emit('message');

eventEmitter.off('message', showMessage);

eventEmitter.emit('message');

Output:

Event listener executed.

The first emit() triggers the listener. After it is removed, the second emit() does not call it.

Removing listeners that are no longer needed helps prevent unintended behavior and memory leaks in long-running applications.

✦ Step 6: Handle Errors with EventEmitter

The Events module treats the special event name error differently from ordinary custom events.

If an EventEmitter emits an error event without an appropriate listener, Node.js normally throws the error, which can terminate the process if it is not handled.

Example:

const EventEmitter = require('node:events');

const eventEmitter = new EventEmitter();

eventEmitter.on('error', (err) => {
    console.error('Handled error:', err.message);
});

eventEmitter.emit(
    'error',
    new Error('Something went wrong')
);

Output:

Handled error: Something went wrong

Registering an error listener allows the application to handle the emitted error.

However, this does not automatically handle every exception or rejected promise in your application. Use appropriate error handling for asynchronous operations as well.

✦ Step 7: Practical Project — Student Registration Events

Let's build a small example that demonstrates how events can be used in a student registration workflow.

When a student registers, the application will:

  1. Display a registration confirmation.

  2. Record a registration message.

  3. Display the student's course.

Create app.js with the following complete code:

const EventEmitter = require('node:events');

const eventEmitter = new EventEmitter();

function registerStudent(name, course) {
    const student = {
        name: name,
        course: course
    };

    eventEmitter.emit('studentRegistered', student);
}

eventEmitter.on('studentRegistered', (student) => {
    console.log('Student Registration Successful!');
    console.log(`Name: ${student.name}`);
    console.log(`Course: ${student.course}`);
});

eventEmitter.on('studentRegistered', (student) => {
    console.log(`Registration activity recorded for ${student.name}.`);
});

registerStudent('Rahul', 'Node.js');

Run the program:

node app.js

Output:

Student Registration Successful!
Name: Rahul
Course: Node.js
Registration activity recorded for Rahul.

❖ How Does This Project Work?

The registerStudent() function creates a student object and emits the studentRegistered event.

Two listeners are registered for that event. One displays the registration details, while the other records an activity message.

This is an example of separating an action from its responses. In a larger application, listeners could perform additional tasks, such as sending notifications or updating in-memory statistics.

For important operations such as sending email or saving data to a database, handle failures and asynchronous work explicitly. Emitting an event alone does not guarantee that those tasks have completed successfully.

✦ Important EventEmitter Methods

Method Purpose
on(event, listener) Register a listener
emit(event, ...args) Trigger an event and pass arguments
once(event, listener) Register a listener for one invocation
off(event, listener) Remove a listener
removeListener(event, listener) Remove a registered listener
removeAllListeners(event) Remove listeners for an event, or all listeners if no event is specified
listenerCount(event) Return the number of listeners for an event

 

 

Use removeAllListeners() carefully because it may remove listeners registered by other parts of your application.

✦ Best Practices for Using EventEmitter

❖ 1. Use Clear Event Names

Choose descriptive names such as studentRegistered, orderCreated, or paymentCompleted.

❖ 2. Keep Listeners Focused

A listener should have a clear responsibility. This makes the code easier to test and maintain.

❖ 3. Handle Errors Properly

Register appropriate error listeners and handle errors from asynchronous operations.

❖ 4. Remove Unnecessary Listeners

In long-running applications, remove listeners when they are no longer required.

❖ 5. Avoid Uncontrolled Event Chains

If events trigger other events indefinitely, the application can become difficult to debug. Keep event flows understandable.

❖ 6. Understand Synchronous Execution

Ordinary EventEmitter listeners execute synchronously by default. Long-running synchronous work inside a listener can delay other work on the event loop.

✦ Frequently Asked Questions (FAQs)

❖ 1. What is EventEmitter in Node.js?

EventEmitter is a class from the built-in Events module that allows objects to emit named events and notify registered listeners.

❖ 2. Do I need to install the Events module?

No. It is included with Node.js and can be imported using require('node:events').

❖ 3. What is the difference between on() and once()?

on() registers a listener that can run each time the event is emitted. once() removes the listener after its first invocation.

❖ 4. Can one event have multiple listeners?

Yes. You can register multiple listeners for the same event, and they are called in registration order by default.

❖ 5. What does emit() do?

The emit() method triggers an event and passes any supplied arguments to the registered listeners.

❖ 6. Where is EventEmitter used in real applications?

It is useful for application notifications, logging, workflow events, and coordinating different components within a Node.js process.

✦ Conclusion

The Node.js Events module provides a practical way to build event-driven applications. With EventEmitter, you can create custom events, register multiple listeners, pass data, remove listeners, and handle special error events.

These concepts are useful when building backend systems, student management applications, order workflows, and other Node.js projects.

At Param Classes, learners can strengthen their backend development skills through practical examples and step-by-step programming tutorials.

Visit Param Classes for programming resources and ParamWebInfo for website development and digital solutions.

←
Post 11 of 40
→