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

Emitting Events in Node.js

Learn how to emit events using EventEmitter, pass data to listeners, and build practical event-driven applications with CIIT Training Institute examples.

In the previous lessons, we learned about EventEmitter and how to register event listeners using on() and once(). In this lesson, we will learn how to emit events using emit() and how registered listeners respond when an event is emitted.

We will use practical examples involving Samadhan and Pradnya, who are working with student enquiries and course admissions at CIIT Training Institute.

1. What Is Emitting an Event?

Emitting an event means notifying an EventEmitter that a particular event has occurred. Node.js provides the emit() method to perform this operation.

When an event is emitted, Node.js calls the listeners registered for that event name. We can also pass additional values to those listeners through the arguments of emit().

For example, when Samadhan adds a new student enquiry to the CIIT Training Institute system, the application can emit a studentEnquiryAdded event. A listener can display a confirmation message or perform another required action.

Remember: on() registers a listener, while emit() emits the event. The listener must be registered for the matching event name to respond to that emission.

2. Syntax of the emit() Method

The emit() method accepts an event name followed by zero or more arguments. These additional arguments are passed to the registered listeners.

Basic Syntax

JavaScript
emitter.emit("eventName");

emitter.emit("eventName", argument1, argument2);

Understanding the Syntax

Part Meaning
emitter The EventEmitter object.
emit() Emits a named event.
"eventName" The name of the event to emit.
argument1 The first optional value passed to listeners.
argument2 The second optional value passed to listeners.

3. First Program Using emit()

Let's create a simple program that emits a welcome event. The registered listener will display a welcome message for CIIT Training Institute.

Step 1: Create a File

Create a JavaScript file named emittingEvents.js.

Step 2: Write the Program

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

const emitter = new EventEmitter();

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

emitter.emit("welcome");

Step 3: Run the Program

Terminal
node emittingEvents.js

Step 4: Expected Output

Output
Welcome to 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("welcome", ...) registers the welcome event listener.
  4. emitter.emit("welcome") emits the event and executes the registered listener.
Result: The welcome message appears because the program emits the same event name for which the listener has been registered.

4. How Does Event Emission Work?

This diagram explains the sequence of registering a listener, emitting an event, and executing the corresponding callback.

Step 1: Create EventEmitter

new EventEmitter()

↓
Step 2: Register Listener

emitter.on("welcome", callback)

↓
Step 3: Emit Event

emitter.emit("welcome")

↓
Step 4: Execute Listener

Display the welcome message.

Note: EventEmitter listeners are normally invoked synchronously when an event is emitted. If no matching listener is registered, the emission does not invoke a callback for that event.

5. Practical Example: CIIT Student Enquiry

Imagine that Samadhan works with student enquiries at CIIT Training Institute. When a new student enquiry is added, the application should display a confirmation message.

We can create a studentEnquiryAdded event and pass the student's name to its listener.

Program

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

const emitter = new EventEmitter();

emitter.on("studentEnquiryAdded", (studentName) => {
    console.log(
        "New student enquiry received: " + studentName
    );
});

emitter.emit("studentEnquiryAdded", "Samadhan");
emitter.emit("studentEnquiryAdded", "Pradnya");

Expected Output

Output
New student enquiry received: Samadhan
New student enquiry received: Pradnya

Explanation

  • The listener is registered for studentEnquiryAdded.
  • The first emission passes "Samadhan" to the listener.
  • The second emission passes "Pradnya" to the same listener.
  • The callback executes for each emission and displays the corresponding name.
Real-world connection: In a complete admissions system, this event could be used to trigger logging, update an enquiry dashboard, or notify another component. Those actions must be implemented separately; emitting an event does not automatically save data to a database.

6. Passing Multiple Arguments with emit()

We can pass multiple values to a listener. This is useful when an event needs to provide more than one piece of information.

For example, Pradnya registers a student for a course at CIIT Training Institute. The event can carry the student's name and course name.

Program

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

const emitter = new EventEmitter();

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

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

Expected Output

Output
Student: Pradnya
Course: Node.js Development

Understanding the Arguments

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

The arguments are passed in order. The first value is received by studentName, and the second value is received by courseName.

7. Event Data Flow Diagram

The following diagram shows how student and course information moves from emit() to the registered listener.

1. Emit Student Event

emit("studentRegistered", "Pradnya", "Node.js Development")

↓
2. Pass Arguments

studentName = "Pradnya"

courseName = "Node.js Development"

↓
3. Listener Receives Values

(studentName, courseName) => { ... }

↓
4. Display Information

Student: Pradnya

Course: Node.js Development

8. Emitting the Same Event Multiple Times

A listener registered with on() can execute every time the same event is emitted, as long as it remains registered.

Program

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

const emitter = new EventEmitter();

emitter.on("courseEnquiry", () => {
    console.log("New course enquiry received.");
});

emitter.emit("courseEnquiry");
emitter.emit("courseEnquiry");
emitter.emit("courseEnquiry");

Expected Output

Output
New course enquiry received.
New course enquiry received.
New course enquiry received.

The event is emitted three times, so the registered listener executes three times. This behavior is useful when an application processes repeated actions, such as receiving multiple enquiries.

9. Understanding the Return Value of emit()

The emit() method returns a Boolean value. It returns true when at least one listener was registered for the specified event and false when no listener was registered for that event.

Program

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

const emitter = new EventEmitter();

emitter.on("courseAdded", () => {
    console.log("Course added successfully.");
});

const result = emitter.emit("courseAdded");

console.log(result);

Expected Output

Output
Course added successfully.
true

Because a listener is registered for courseAdded, the event executes that listener and emit() returns true.

Important Points

  • emit() is used to emit a named event.
  • Register a listener with on() before emitting an event if it must receive that emission.
  • Event names used in on() and emit() must match.
  • Additional arguments passed to emit() are received by the listener in the same order.
  • A listener registered with on() can respond to repeated emissions.
  • emit() returns true if the event has registered listeners and false otherwise.

Summary

In this lesson, we learned how to emit events in Node.js using emit(). We created event listeners, emitted events for CIIT Training Institute examples, passed student names and course information to callbacks, emitted the same event multiple times, and understood the Boolean return value of emit(). These concepts help us build event-driven applications in which different components can respond to specific occurrences.