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

Events Introduction in Node.js

Learn how events work in Node.js and how applications can respond to actions or occurrences using an event-driven approach.

Node.js provides an event-driven programming model that helps applications respond to events such as incoming requests, completed operations, and user-defined actions. In this tutorial, we will understand events, event listeners, and the EventEmitter class using simple JavaScript examples.

1. What Are Events in Node.js?

An event is an action or occurrence that a program can detect and respond to. For example, an application may respond when a file is opened, a request is received, or a task is completed.

In Node.js, event-driven programming allows us to define what should happen when a particular event occurs. We can register a function called an event listener and execute it when the corresponding event is emitted.

For example, when a user completes a task in our Task Manager, the application could emit a taskCompleted event. A listener could then display a confirmation message.

Remember: An event represents something that happens. An event listener is a function that responds when that event is emitted or triggered.

2. Why Are Events Used in Node.js?

Events help different parts of an application respond to occurrences without requiring every part of the application to call every other part directly.

Example Event Possible Response
Task Manager taskAdded Display a task-added message.
File Stream data Process a received data chunk.
HTTP Server request Process an incoming request.
File Reading end Respond when a readable stream ends.
Custom Application userRegistered Display a confirmation or initiate another action.

3. How Does Event Handling Work?

Event handling usually involves registering a listener and emitting the event when the application needs to notify interested code.

1. Create an EventEmitter

Create an object to manage events

↓
2. Register a Listener

Define the function that responds to an event

↓
3. Emit an Event

Notify listeners that the event occurred

↓
4. Execute the Listener

Run the registered callback function

Note: With Node.js EventEmitter, listeners are normally called synchronously when the event is emitted, unless the listener itself schedules asynchronous work.

4. What Is EventEmitter?

EventEmitter is a class provided by the built-in Node.js events module. It allows us to register listeners, emit named events, and pass data to listeners.

To use it, we import the class from the node:events module and create an instance.

Basic Syntax

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

const emitter = new EventEmitter();

Understanding the Code

Code Meaning
require("node:events") Loads Node.js's built-in events module.
EventEmitter The class used to create event-emitting objects.
new EventEmitter() Creates an instance that can register and emit events.

5. First Event Handling Program

Let's create a simple program that registers a listener for an event named welcome and emits that event.

Step 1: Create a File

Create a JavaScript file named events.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 Events!");
});

emitter.emit("welcome");

Step 3: Run the Program

Terminal
node events.js

Step 4: Expected Output

Output
Welcome to Node.js Events!

Step 5: Understand the Code

  1. new EventEmitter() creates an event emitter.
  2. emitter.on("welcome", ...) registers a listener for the welcome event.
  3. emitter.emit("welcome") emits the event.
  4. The registered listener executes and displays the message.
Result: The message appears because the program emits the same event name for which a listener has been registered.

6. Passing Data Through Events

An event can carry data. When an event is emitted with arguments, its listener receives those arguments.

Example: Task Added Event

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

const emitter = new EventEmitter();

emitter.on("taskAdded", (taskName) => {
    console.log("New task added: " + taskName);
});

emitter.emit("taskAdded", "Learn Node.js");

Output

Output
New task added: Learn Node.js

Explanation: The second argument passed to emit() is "Learn Node.js". The listener receives that value through its taskName parameter.

7. Event Data Flow Diagram

This diagram explains how data passes from the event emitter to the registered listener.

Emit Event

emit("taskAdded", "Learn Node.js")

↓
Pass Event Argument

"Learn Node.js"

↓
Listener Receives Data

(taskName) => { ... }

↓
Display Message

New task added: Learn Node.js

8. Registering Multiple Listeners

We can register more than one listener for the same event. When that event is emitted, the registered listeners are called in their registration order.

Example

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

const emitter = new EventEmitter();

emitter.on("taskCompleted", () => {
    console.log("Task completion recorded.");
});

emitter.on("taskCompleted", () => {
    console.log("Congratulations! Task completed.");
});

emitter.emit("taskCompleted");

Output

Output
Task completion recorded.
Congratulations! Task completed.

Both listeners respond to the same event. This can be useful when different parts of an application need to respond to the same occurrence.

9. Important EventEmitter Methods

Method Purpose
emitter.on() Registers a listener for an event.
emitter.emit() Emits an event and passes optional arguments.
emitter.once() Registers a listener that runs at most once.
emitter.off() Removes a specific registered listener.
emitter.removeAllListeners() Removes listeners for an event or all events on that emitter.

We will explore these methods in detail in the upcoming EventEmitter lessons.

Important Points

  • An event represents an action or occurrence.
  • Event listeners define what happens when an event is emitted.
  • Node.js provides the built-in node:events module.
  • on() registers listeners and emit() emits events.
  • EventEmitter can pass data to listeners through arguments.
  • Multiple listeners can respond to the same event.

Summary

Node.js supports event-driven programming, allowing applications to respond to different occurrences. We learned what events and event listeners are, how to create an EventEmitter, and how to register listeners using on() and trigger them using emit(). We also passed data through events and registered multiple listeners for the same event. These concepts form the foundation for using EventEmitter in practical Node.js applications.