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

Custom Events in Node.js

Learn how to create custom events, register listeners, pass data through events, and build event-driven applications using practical CIIT Training Institute examples.

In the previous lesson, we learned how to remove event listeners using off(), removeListener(), and removeAllListeners(). In this lesson, we will learn how to create and use custom events with Node.js EventEmitter.

A custom event allows us to define an event name according to our application's requirements. For example, CIIT Training Institute can use events such as studentRegistered, courseEnquiryReceived, and paymentCompleted to represent different application activities.

1. What Are Custom Events?

A custom event is an event that we define for a specific purpose in our application. Node.js allows us to create custom event names and use EventEmitter to notify registered listeners when those events occur.

For example, when Samadhan registers a new student at CIIT Training Institute, the application can emit a studentRegistered event. A listener can respond by displaying a confirmation message or performing another application task.

Similarly, when Pradnya receives a course enquiry, the application can emit a courseEnquiryReceived event and pass the student's information to the listener.

Remember: A custom event name is defined by the application developer. EventEmitter provides the methods used to register listeners and emit these events.

2. Why Do We Use Custom Events?

Custom events allow different parts of an application to respond to important occurrences without requiring the code that emits the event to directly call every listener.

Custom Event When It Occurs Possible Response
studentRegistered A student registers for a course. Display a registration confirmation.
courseEnquiryReceived A student submits a course enquiry. Display an enquiry notification.
paymentCompleted A payment workflow confirms completion. Display a payment confirmation.
taskCompleted A task is marked as completed. Record or display the completion status.
Important: Emitting an event does not automatically save information to a database, send an email, or process a payment. Those operations require their own implementation.

3. Creating Your First Custom Event

To create a custom event, we first create an EventEmitter object, register a listener for our chosen event name, and then emit that event.

Step 1: Create a JavaScript File

Create a file named customEvents.js.

Step 2: Write the Program

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

const emitter = new EventEmitter();

emitter.on("studentRegistered", () => {
    console.log("Student registered successfully at CIIT Training Institute!");
});

emitter.emit("studentRegistered");

Step 3: Run the Program

Terminal
node customEvents.js

Step 4: Expected Output

Output
Student registered successfully at CIIT Training Institute!

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("studentRegistered", ...) registers a listener for our custom event.
  4. emitter.emit("studentRegistered") emits the event and executes the registered listener.
Result: The custom event is emitted, and the registered callback displays the confirmation message.

4. Custom Event Flow Diagram

This diagram explains how a custom event works inside a Node.js application.

1. Create EventEmitter

new EventEmitter()

↓
2. Register Custom Event Listener

emitter.on("studentRegistered", callback)

↓
3. Emit Custom Event

emitter.emit("studentRegistered")

↓
4. Execute Listener

Display the student registration message.

Note: The listener should be registered before the event is emitted if it needs to receive that emission.

5. Passing Data Through Custom Events

Custom events can carry information. We pass values as additional arguments to emit(), and the listener receives those values through its function parameters.

For example, Samadhan registers a student for a course. The application can emit the student's name and the course name.

Example: Student Registration

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

const emitter = new EventEmitter();

emitter.on("studentRegistered", (studentName, courseName) => {
    console.log("Student Name: " + studentName);
    console.log("Course Name: " + courseName);
});

emitter.emit(
    "studentRegistered",
    "Samadhan",
    "Node.js Development"
);

Expected Output

Output
Student Name: Samadhan
Course Name: Node.js Development

Understanding the Arguments

Emitted Value Listener Parameter
"Samadhan" studentName
"Node.js Development" courseName

The first argument is received by studentName, and the second argument is received by courseName.

6. Creating Multiple Custom Events

We can register multiple custom events on the same EventEmitter object. Each event can have its own listener and purpose.

In this example, Pradnya handles course enquiries while Samadhan handles student registration notifications.

Program

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

const emitter = new EventEmitter();

emitter.on("courseEnquiryReceived", (studentName) => {
    console.log("Pradnya received an enquiry from " + studentName);
});

emitter.on("studentRegistered", (studentName) => {
    console.log("Samadhan registered student " + studentName);
});

emitter.emit("courseEnquiryReceived", "Amit");
emitter.emit("studentRegistered", "Neha");

Expected Output

Output
Pradnya received an enquiry from Amit
Samadhan registered student Neha

The first event invokes the course enquiry listener. The second event invokes the student registration listener. Each listener responds to its corresponding event name.

7. CIIT Training Institute Event Flow

This diagram shows how two different application activities can use custom events and separate listeners.

CIIT Training Institute Application

Student enquiry and registration activities

Course Enquiry

Emit courseEnquiryReceived

↓
Pradnya's Listener

Display the enquiry notification.

Student Registration

Emit studentRegistered

↓
Samadhan's Listener

Display the registration notification.

8. Best Practices for Custom Event Names

Choosing meaningful event names makes code easier to understand and maintain. Event names should clearly describe the occurrence that the application is reporting.

Less Descriptive More Descriptive Reason
event1 studentRegistered Clearly describes student registration.
data courseEnquiryReceived Identifies the specific application occurrence.
done paymentCompleted Explains what has been completed.
action taskCompleted Makes the event's purpose clearer.
Tip: Use consistent naming conventions throughout the project. Names such as studentRegistered and courseEnquiryReceived are examples of descriptive camelCase event names.

9. Common Mistakes with Custom Events

Mistake 1: Event Name Mismatch

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

const emitter = new EventEmitter();

emitter.on("studentRegistered", () => {
    console.log("Student registered!");
});

emitter.emit("courseEnquiryReceived");

Output

Output
// No output

The listener is registered for studentRegistered, but the program emits courseEnquiryReceived. Because the event names are different, the listener does not execute.

Mistake 2: Emitting Before Registering

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

const emitter = new EventEmitter();

emitter.emit("studentRegistered");

emitter.on("studentRegistered", () => {
    console.log("Student registered!");
});

Output

Output
// No output

The event is emitted before the listener is registered. EventEmitter does not automatically replay that earlier event to listeners registered later.

Correction: Register the listener first, then emit the event when the application needs to notify the listener.

Important Points

  • Custom events are application-defined event names.
  • Node.js EventEmitter provides on() and emit() to work with custom events.
  • Event names must match for the registered listener to respond.
  • Additional arguments passed to emit() are received by listener parameters in order.
  • Multiple custom events can be managed by the same EventEmitter object.
  • Emitting a custom event does not automatically persist data or perform external operations.

Summary

In this lesson, we learned how to create custom events in Node.js using EventEmitter. We registered listeners, emitted events, passed student and course information through callback arguments, created multiple custom events, and explored common mistakes involving event names and registration order. We also used CIIT Training Institute examples involving Samadhan and Pradnya to understand practical event-driven programming.