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

EventEmitter in Node.js

Learn how to create an EventEmitter, register event listeners, emit events, and pass data between parts of a Node.js application.

In the previous lesson, we learned what events are and how event-driven programming works. Node.js provides the built-in node:events module, which includes the EventEmitter class. We can use it to create named events and run callback functions when those events are emitted.

1. What Is EventEmitter?

EventEmitter is a class from Node.js's built-in events module. An EventEmitter object lets us register functions as listeners and notify those listeners when a named event occurs.

Think of a Task Manager application. When a task is added, the application can emit a taskAdded event. A listener can respond by displaying a message or recording the activity.

Remember: on() registers a listener, while emit() emits an event and calls the listeners registered for that event.

2. Importing EventEmitter

The events module is included with Node.js, so you do not need to install an external npm package. In a CommonJS project, import it using require().

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

const emitter = new EventEmitter();

Understanding the Code

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

The node: prefix explicitly identifies a built-in Node.js module.

3. First EventEmitter Program

Let's register a listener for an event named welcome and then emit that event.

Step 1: Create a File

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

emitter.emit("welcome");

Step 3: Run the Program

Terminal
node eventEmitter.js

Step 4: Expected Output

Output
Welcome to Node.js EventEmitter!

Step 5: Understand the Code

  1. new EventEmitter() creates an emitter object.
  2. emitter.on("welcome", ...) registers a listener for the welcome event.
  3. () => { ... } is the callback function that runs when the event is emitted.
  4. emitter.emit("welcome") emits the event and invokes the registered listener.
Result: The message appears because the event name passed to emit() matches the event name registered with on().

4. EventEmitter Flow Diagram

The following flow shows how an EventEmitter calls a registered listener.

1. Create Emitter

new EventEmitter()

↓
2. Register Listener

emitter.on("welcome", callback)

↓
3. Emit Event

emitter.emit("welcome")

↓
4. Listener Executes

The callback displays the welcome message.

EventEmitter listeners are called synchronously, in registration order, when the event is emitted. A listener can schedule asynchronous work if needed.

5. Passing Data to an Event Listener

We can pass values to a listener by providing them as additional arguments to emit(). The listener receives those values as function parameters.

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 value "Learn Node.js" is passed as the second argument to emit(). The listener receives it in the taskName parameter.

6. Registering Multiple Listeners

More than one listener can be registered for the same event. When the event is emitted, the listeners run in the order in which they were registered.

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 callbacks respond to the same taskCompleted event. This is useful when different parts of an application need to react to one occurrence.

7. Using once() for a One-Time Listener

The once() method registers a listener that runs only the first time the specified event is emitted.

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

            const emitter = new EventEmitter();

            emitter.once("start", () => {
            console.log("The process has started.");
            });

            emitter.emit("start");
            emitter.emit("start");

Output

Output
The process has started.

Although start is emitted twice, the listener runs only once because it was registered with once().

8. Important EventEmitter Methods

MethodPurpose
on(eventName, listener)Registers a listener for an event.
emit(eventName, ...args)Emits an event and optionally passes arguments to listeners.
once(eventName, listener)Registers a listener that runs at most once.
off(eventName, listener)Removes a specific listener from an event.
removeAllListeners(eventName)Removes listeners for the specified event; without an event name, removes all listeners from that emitter.

We will explore registering, emitting, and removing events in the next lessons.

Important Points

  • EventEmitter is available from Node.js's built-in node:events module.
  • on() registers a listener and emit() emits an event.
  • The event name used by on() must match the name passed to emit().
  • Extra arguments passed to emit() are received by listener parameters.
  • once() registers a listener that runs only once.

Summary

In this lesson, we learned that Node.js EventEmitter objects let us register listeners and emit named events. We created an emitter, used on() to register a callback, used emit() to trigger it, passed data to a listener, registered multiple listeners, and used once() for a one-time response. These basics prepare us to work with event registration and emission in more detail.