Lesson 15 of 50 – Events Module
30% Completed
30%

Node.js Events Module

Events are an important part of Node.js. They allow different parts of an application to communicate when something happens. For example, an application can respond when a user connects, a file finishes loading, or a custom event is triggered.

In simple words: An event is an action or occurrence that a program can detect and respond to.

1. What Are Events in Node.js?

Node.js uses an event-driven programming model. Code can register functions that run when particular events occur.

Common examples of events include:

  • A file has finished reading.
  • A user sends a request to a server.
  • A timer finishes.
  • A custom event is emitted by your program.

2. What Is the Events Module?

Node.js provides a built-in module named node:events. It includes the EventEmitter class, which lets us create, emit, and handle custom events.

Example: Import the Events Module
const EventEmitter = require('node:events');

console.log("Events Module Loaded");

Output:

Events Module Loaded

This example uses CommonJS syntax. In an ES Module project, use import { EventEmitter } from 'node:events';.

3. Creating an EventEmitter Object

To work with custom events, create an instance of the EventEmitter class.

Example: Create an EventEmitter
const EventEmitter = require('node:events');

const event = new EventEmitter();

console.log("Event object created");

Output:

Event object created

The event object can now register listeners and emit custom events.

4. The on() Method

The on() method registers a listener function. The listener runs whenever the specified event is emitted.

Example: Register an Event Listener
const EventEmitter = require('node:events');

const event = new EventEmitter();

event.on('greet', function() {
    console.log("Hello Students!");
});

event.emit('greet');

Output:

Hello Students!

The listener is registered with on(). When emit('greet') is called, the listener executes.

5. The emit() Method

The emit() method triggers an event. If listeners have been registered for that event, they are called.

Example: Emit an Event
const EventEmitter = require('node:events');

const event = new EventEmitter();

event.on('start', function() {
    console.log("Program started");
});

event.emit('start');

Output:

Program started
Register the listener before emitting the event if you want it to handle that emission. Ordinary EventEmitter events are not automatically stored for future listeners.

6. Passing Arguments to an Event

We can pass data to listeners by supplying arguments to emit(). The listener receives those arguments in the same order.

Example: Pass a Student Name
const EventEmitter = require('node:events');

const event = new EventEmitter();

event.on('student', function(name) {
    console.log("Student Name:", name);
});

event.emit('student', 'Amit');

Output:

Student Name: Amit

7. Passing Multiple Arguments

An event can pass multiple values to its listener, such as a student's name, age, and course.

Example: Multiple Arguments
const EventEmitter = require('node:events');

const event = new EventEmitter();

event.on('student', function(name, age, course) {
    console.log("Name:", name);
    console.log("Age:", age);
    console.log("Course:", course);
});

event.emit('student', 'Rahul', 20, 'Node.js');

Output:

Name: Rahul
Age: 20
Course: Node.js

8. Registering Multiple Listeners

We can register multiple listeners for the same event. Each listener runs when that event is emitted.

Example: Multiple Listeners
const EventEmitter = require('node:events');

const event = new EventEmitter();

event.on('message', function() {
    console.log("First listener");
});

event.on('message', function() {
    console.log("Second listener");
});

event.emit('message');

Output:

First listener
Second listener

For ordinary synchronous listeners, Node.js calls listeners in registration order.

9. The once() Method

The once() method registers a listener that runs only once. After its first execution, that listener is removed.

Example: Run an Event Once
const EventEmitter = require('node:events');

const event = new EventEmitter();

event.once('login', function() {
    console.log("Login event handled");
});

event.emit('login');
event.emit('login');
event.emit('login');

Output:

Login event handled

Even though the event is emitted three times, the listener runs only on its first emission.

10. Removing an Event Listener

The off() method removes a previously registered listener. The same function reference must be supplied.

Example: Remove a Listener
const EventEmitter = require('node:events');

const event = new EventEmitter();

function showMessage() {
    console.log("Hello Students");
}

event.on('message', showMessage);

event.emit('message');

event.off('message', showMessage);

event.emit('message');

Output:

Hello Students

The first emission calls the listener. The second emission does not call it because it has been removed.

11. The listenerCount() Method

The listenerCount() method returns the number of listeners registered for a particular event on an EventEmitter instance.

Example: Count Listeners
const EventEmitter = require('node:events');

const event = new EventEmitter();

event.on('data', function() {});
event.on('data', function() {});

console.log(event.listenerCount('data'));

Output:

2

12. Practical Example: Student Registration Event

Let's create an event that runs whenever a student registers in an application.

Example: Student Registration
const EventEmitter = require('node:events');

const studentEvents = new EventEmitter();

studentEvents.on('registered', function(name, course) {
    console.log("New Student Registered");
    console.log("Name:", name);
    console.log("Course:", course);
});

studentEvents.emit('registered', 'Amit', 'Node.js');

Output:

New Student Registered
Name: Amit
Course: Node.js

This is a simple example of using events to separate the action that announces a registration from the code that responds to it.

13. Common EventEmitter Methods

Method Purpose
on() Registers a listener.
emit() Triggers an event.
once() Registers a listener that runs once.
off() Removes a specific listener.
removeListener() Removes a specific listener.
removeAllListeners() Removes listeners for one event or all events.
listenerCount() Returns the number of listeners for an event.

14. Practical Assignment

Practice Task
Create a simple course enrollment event program.
  1. Import the EventEmitter class.
  2. Create an EventEmitter object.
  3. Register a listener named enroll.
  4. Make the listener accept a student's name and course.
  5. Display both values when the event is triggered.
  6. Emit the event for two students.
  7. Register another event using once() and trigger it twice.

Starter code:

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

const school = new EventEmitter();

school.on('enroll', function(name, course) {
    console.log(name + " enrolled in " + course);
});

school.emit('enroll', 'Amit', 'Node.js');
school.emit('enroll', 'Rahul', 'JavaScript');

Expected output:

Amit enrolled in Node.js
Rahul enrolled in JavaScript

🧠 Quiz – Node.js Events Module

Select the correct answer for each question.

1. Which method triggers an event?



2. Which method registers a listener that runs only once?



3. Which class is used to create custom event emitters?