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

Registering Events in Node.js

Learn how to register event listeners in Node.js using on() and once(), handle named events, and respond to application actions.

In the previous lesson, we learned about the EventEmitter class. Now, we will learn how to register event listeners. A listener is a callback function that executes when its associated event is emitted. Node.js provides methods such as on() and once() to register listeners.

1. What Is Registering an Event?

Registering an event means telling an EventEmitter which function should execute when a particular event is emitted.

For example, in our Task Manager application, we can register a listener for the taskAdded event. When a new task is added and the event is emitted, the registered function displays a confirmation message.

Remember: Registering a listener does not automatically emit the event. The listener waits until the corresponding event is emitted.

2. Using the on() Method

The on() method registers a listener for a named event. The listener executes whenever that event is emitted, provided the listener remains registered.

Syntax

JavaScript
emitter.on("eventName", callbackFunction);

Understanding the Syntax

Part Meaning
emitter The EventEmitter object.
on() Registers an event listener.
"eventName" The name of the event to listen for.
callbackFunction The function that executes when the event is emitted.

3. Registering Your First Event Listener

Let's register a listener for an event named welcome.

Step 1: Create a File

Create a JavaScript file named registerEvent.js.

Step 2: Write the Program

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

const emitter = new EventEmitter();

emitter.on("welcome", () => {
    console.log("Welcome to Node.js!");
});

emitter.emit("welcome");

Step 3: Run the Program

Terminal
node registerEvent.js

Step 4: Expected Output

Output
Welcome to Node.js!

Step 5: Understand the Code

  1. require("node:events") imports the built-in EventEmitter class.
  2. new EventEmitter() creates an emitter object.
  3. emitter.on("welcome", ...) registers the listener.
  4. emitter.emit("welcome") emits the event and executes the registered callback.
Result: The registered listener displays the welcome message when the welcome event is emitted.

4. Event Listener Registration Flow

The following diagram explains the relationship between event registration and event emission.

1. Create EventEmitter

new EventEmitter()

↓
2. Register Listener

emitter.on("welcome", callback)

↓
3. Emit Event

emitter.emit("welcome")

↓
4. Execute Callback

The registered function runs.

Note: Registering a listener and emitting an event are two separate operations. Register the listener before emitting the event if you want it to receive that emission.

5. Registering Multiple Event Listeners

We can register listeners for different event names on the same EventEmitter object. Each listener responds to its corresponding event.

Example: Task Manager

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

const emitter = new EventEmitter();

emitter.on("taskAdded", () => {
    console.log("A new task was added.");
});

emitter.on("taskDeleted", () => {
    console.log("A task was deleted.");
});

emitter.emit("taskAdded");
emitter.emit("taskDeleted");

Output

Output
A new task was added.
A task was deleted.

Explanation: The taskAdded listener executes when taskAdded is emitted. Similarly, the taskDeleted listener executes when taskDeleted is emitted.

6. Registering a Named Callback Function

Instead of writing an anonymous arrow function inside on(), we can define a named function and pass its reference to the listener registration method.

Example

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

const emitter = new EventEmitter();

function handleTaskAdded() {
    console.log("Task added successfully!");
}

emitter.on("taskAdded", handleTaskAdded);

emitter.emit("taskAdded");

Output

Output
Task added successfully!

Here, handleTaskAdded is passed as a function reference. We do not write handleTaskAdded() inside on(), because we want the EventEmitter to call it when the event is emitted.

7. Registering a One-Time Listener with once()

The once() method registers a listener that executes at most one time for the specified event. After the first execution, that listener is automatically removed.

Example

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

const emitter = new EventEmitter();

emitter.once("userLogin", () => {
    console.log("User login event handled.");
});

emitter.emit("userLogin");
emitter.emit("userLogin");

Output

Output
User login event handled.

Although the event is emitted twice, the callback executes only once because it was registered using once().

8. Difference Between on() and once()

Feature on() once()
Purpose Registers a regular listener. Registers a one-time listener.
Number of executions Can execute on every emission. Executes at most once.
Automatic removal Not automatically removed after execution. Removed after its first execution.
Typical use Repeated application events. One-time initialization or notification.

9. Common Mistake: Event Name Mismatch

A listener responds only to the event name for which it is registered. If we emit a different event name, that listener will not execute.

Incorrect Example

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

const emitter = new EventEmitter();

emitter.on("taskAdded", () => {
    console.log("Task added!");
});

emitter.emit("taskDeleted");

Output

Output
// No output

Why? The listener is registered for taskAdded, but the program emits taskDeleted. These are different event names.

Correction: Use emitter.emit("taskAdded") if you want the registered taskAdded listener to execute.

Important Points

  • on() registers a listener for an event.
  • once() registers a listener that executes at most once.
  • Registering a listener does not automatically emit an event.
  • The event name used in registration must match the emitted event name.
  • Multiple listeners can be registered for different events or for the same event.
  • A named callback can be passed to on() as a function reference.

Summary

In this lesson, we learned how to register event listeners in Node.js using on() and once(). We created listeners for different events, used named callback functions, compared regular and one-time listeners, and understood why event names must match. In the next lesson, we will learn how to emit events and pass data to their listeners.