Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

Removing Event Listeners in Node.js

Learn how to remove event listeners using off() and removeListener(), remove multiple listeners, and manage events in real-world Node.js applications.

In the previous lesson, we learned how to emit events using emit() and pass data to event listeners. In this lesson, we will learn how to remove registered listeners when they are no longer required.

We will use examples from CIIT Training Institute, where Samadhan and Pradnya work with student enquiries and course notifications. These examples will help us understand when and why an application may need to remove an event listener.

1. What Is Removing an Event Listener?

Removing an event listener means unregistering a previously registered callback function from an EventEmitter object. After removal, that listener will no longer respond to future emissions of the specified event.

For example, Samadhan may register a listener to receive notifications when a new student enquiry is added. If that listener is no longer required, the application can remove it so that it does not process future notifications.

Remember: Removing a listener does not delete the event itself. It removes a particular callback from the emitter. Other listeners registered for the same event can continue to execute.

2. Why Do We Remove Event Listeners?

Applications may register listeners temporarily or dynamically. Removing listeners when they are no longer needed helps keep event handling predictable and can prevent unwanted callback executions.

Situation Example Purpose
Notification completed Pradnya no longer needs a temporary notification. Stop future callbacks for that listener.
Task completed A temporary task-processing listener is no longer needed. Avoid unnecessary processing.
Component cleanup A service stops listening for an application event. Prevent unwanted retained references and callbacks.
Listener replacement Samadhan changes a notification handler. Remove the old handler before registering the replacement.

3. Using the off() Method

The off() method removes a specific listener from an event. It requires the event name and the same function reference that was used to register the listener.

Syntax

JavaScript
emitter.off("eventName", listenerFunction);

Understanding the Syntax

Part Meaning
emitter The EventEmitter object.
off() Removes a registered listener.
eventName The event from which the listener must be removed.
listenerFunction The original callback function reference.
Important: You must pass the same function reference used during registration. Creating a new arrow function with identical code does not identify the previously registered callback.

4. First Program: Removing a Listener

Let's create a listener for a welcome event, execute it once, remove it, and then emit the event again.

Step 1: Create a File

Create a JavaScript file named removingListeners.js.

Step 2: Write the Program

JavaScript
const EventEmitter = require("node:events");

const emitter = new EventEmitter();

function welcomeMessage() {
    console.log("Welcome to CIIT Training Institute!");
}

emitter.on("welcome", welcomeMessage);

emitter.emit("welcome");

emitter.off("welcome", welcomeMessage);

emitter.emit("welcome");

Step 3: Run the Program

Terminal
node removingListeners.js

Step 4: Expected Output

Output
Welcome to CIIT Training Institute!

Step 5: Understand the Code

  1. welcomeMessage() defines the callback function.
  2. emitter.on("welcome", welcomeMessage) registers the listener.
  3. emitter.emit("welcome") executes the callback and prints the message.
  4. emitter.off("welcome", welcomeMessage) removes the listener.
  5. The second emit() call does not print anything because the listener has been removed.
Result: The welcome message appears only once because the listener is removed before the second event emission.

5. Event Listener Removal Flow Diagram

This diagram explains how a listener is registered, executed, removed, and prevented from responding to later emissions.

1. Register Listener

emitter.on("welcome", welcomeMessage)

↓
2. Emit Event

emitter.emit("welcome")

↓
3. Remove Listener

emitter.off("welcome", welcomeMessage)

↓
4. Emit Again

The removed listener no longer executes.

6. Practical Example: CIIT Student Notifications

Imagine that Samadhan and Pradnya are working on a student enquiry system at CIIT Training Institute.

Samadhan registers a listener to receive student enquiry notifications. Pradnya registers another listener for the same event. Later, Samadhan's listener is removed, but Pradnya's listener must continue to work.

Program

JavaScript
const EventEmitter = require("node:events");

const emitter = new EventEmitter();

function samadhanNotification(studentName) {
    console.log(
        "Samadhan received enquiry for: " + studentName
    );
}

function pradnyaNotification(studentName) {
    console.log(
        "Pradnya received enquiry for: " + studentName
    );
}

emitter.on("studentEnquiry", samadhanNotification);
emitter.on("studentEnquiry", pradnyaNotification);

console.log("First enquiry:");

emitter.emit("studentEnquiry", "Amit");

emitter.off("studentEnquiry", samadhanNotification);

console.log("Second enquiry:");

emitter.emit("studentEnquiry", "Neha");

Expected Output

Output
First enquiry:
Samadhan received enquiry for: Amit
Pradnya received enquiry for: Amit
Second enquiry:
Pradnya received enquiry for: Neha

Explanation

  • Both Samadhan and Pradnya register listeners for studentEnquiry.
  • When the first enquiry is emitted, both listeners execute.
  • The off() method removes only Samadhan's listener.
  • When the second enquiry is emitted, Pradnya's listener still executes because it remains registered.
Key Learning: Removing one listener does not automatically remove other listeners registered for the same event.

7. off() and removeListener()

Node.js provides both off() and removeListener() to remove a specific event listener. They perform the same listener-removal operation.

Using off()

JavaScript
emitter.off("courseAdded", courseHandler);

Using removeListener()

JavaScript
emitter.removeListener("courseAdded", courseHandler);
Method Purpose
off() Removes a specific listener from an event.
removeListener() Performs the same listener-removal operation.
Required arguments The event name and original listener reference.

In modern Node.js code, off() is a concise option. Both methods are available on EventEmitter objects.

8. Using removeAllListeners()

The removeAllListeners() method removes all listeners for a specified event. If no event name is supplied, it removes all listeners registered on that emitter.

Use this method carefully because other parts of an application may depend on the listeners being removed.

Example: Remove All Listeners for One Event

JavaScript
const EventEmitter = require("node:events");

const emitter = new EventEmitter();

emitter.on("courseUpdate", () => {
    console.log("Samadhan received course update.");
});

emitter.on("courseUpdate", () => {
    console.log("Pradnya received course update.");
});

console.log("Before removing listeners:");

emitter.emit("courseUpdate");

emitter.removeAllListeners("courseUpdate");

console.log("After removing listeners:");

emitter.emit("courseUpdate");

Expected Output

Output
Before removing listeners:
Samadhan received course update.
Pradnya received course update.
After removing listeners:

Before removal, both listeners execute. After removeAllListeners("courseUpdate"), neither listener executes when the event is emitted again.

Important: Calling removeAllListeners() without an event name removes all listeners from that emitter. Avoid doing this on shared emitters unless you intend to remove every listener.

9. Removing One Listener vs All Listeners

This diagram compares removing one callback with removing every listener registered for an event.

Event: studentEnquiry

Samadhan's listener + Pradnya's listener

Option A: off()

Remove Samadhan's listener only.

Samadhan: Removed
Pradnya: Still active
Option B: removeAllListeners()

Remove all listeners for the event.

Samadhan: Removed
Pradnya: Removed

10. Common Mistake: Using a Different Function

A common mistake is passing a new arrow function to off() instead of the original registered function. Although the code inside the functions may look identical, they are different function objects.

Incorrect Example

JavaScript
const EventEmitter = require("node:events");

const emitter = new EventEmitter();

emitter.on("welcome", () => {
    console.log("Welcome to CIIT Training Institute!");
});

emitter.off("welcome", () => {
    console.log("Welcome to CIIT Training Institute!");
});

emitter.emit("welcome");

Output

Output
Welcome to CIIT Training Institute!

The listener remains registered because the function passed to off() is not the same function reference that was passed to on().

Correct Example

JavaScript
const EventEmitter = require("node:events");

const emitter = new EventEmitter();

function welcomeMessage() {
    console.log("Welcome to CIIT Training Institute!");
}

emitter.on("welcome", welcomeMessage);

emitter.off("welcome", welcomeMessage);

emitter.emit("welcome");

Output

Output
// No output
Remember: Save the callback function in a variable or use a named function when you need to remove that exact listener later.

Important Points

  • off() removes a specific registered listener.
  • removeListener() provides the same removal operation.
  • The original callback function reference must be supplied.
  • Removing one listener does not remove other listeners for the same event.
  • removeAllListeners(eventName) removes all listeners for the specified event.
  • Use removeAllListeners() carefully because it can affect other parts of an application.

Summary

In this lesson, we learned how to remove event listeners in Node.js using off() and removeListener(). We also used removeAllListeners() to remove multiple listeners, explored practical CIIT Training Institute examples involving Samadhan and Pradnya, and learned why the original callback reference is important. In the next lesson, we will explore how to create and use custom events in Node.js applications.