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

Node.js Architecture

Node.js uses an event-driven, non-blocking I/O architecture. This helps it handle multiple requests efficiently without creating a separate JavaScript execution thread for every request.

1. What Is Node.js Architecture?

Architecture means the internal structure of a system and how its different components work together.

Node.js architecture explains how JavaScript code is executed, how input/output operations are handled, and how completed operations return their results to the program.

For example, when Samadhan requests a file from a Node.js server, Node.js can start reading the file without blocking other JavaScript work while the file operation is waiting to finish.

Remember: Node.js commonly uses a single JavaScript execution thread with an Event Loop. Some background operations use operating-system facilities or libuv's worker pool. It does not mean every operation runs on the same thread.

2. Main Components of Node.js

The following components work together to execute JavaScript and handle asynchronous operations.

Component Simple Explanation Responsibility
V8 Engine Executes JavaScript code. Compiles and runs JavaScript.
Event Loop Coordinates pending callbacks. Helps Node.js process asynchronous work.
libuv A library used by Node.js. Provides the event loop and asynchronous I/O support.
Node.js APIs Features available to JavaScript programs. Provide access to files, networking, timers, and more.
Operating System The system on which Node.js runs. Provides facilities for networking, files, and other operations.

3. Node.js Architecture Diagram

This simplified diagram shows how a JavaScript application interacts with Node.js and its supporting components.

JavaScript Application

Application code

↓
Node.js Runtime APIs

File System, HTTP, Timers, and other APIs

V8 Engine

Executes JavaScript code

libuv

Event Loop and asynchronous I/O support

↓
Operating System

Networking, file operations, and other system services

Note: This is a simplified learning diagram. The actual internal architecture has additional components and interactions.

4. What Is the V8 Engine?

V8 is the JavaScript engine developed by Google. Node.js uses V8 to execute JavaScript code.

When Pradnya writes JavaScript statements, V8 processes the code and executes it. V8 also uses compilation and optimization techniques to improve execution performance.

Example

JavaScript
let a = 10;
let b = 20;

console.log(a + b);

Output

Output
30

Explanation: V8 executes the JavaScript code. The addition operation produces 30, and console.log() displays it.

5. What Is libuv?

libuv is a library used by Node.js to support asynchronous operations and the Event Loop.

It helps Node.js handle operations such as file-system work, timers, and networking. Depending on the operation, libuv can use operating-system facilities or its worker pool.

For example, Samadhan can request that a file be read. Instead of waiting synchronously for the entire operation, he can use an asynchronous file API and handle the result in a callback.

In simple words: V8 executes JavaScript. libuv supports the event loop and asynchronous operations. They work together as part of Node.js.

6. What Is the Event Loop?

The Event Loop helps Node.js coordinate asynchronous callbacks. It allows JavaScript to continue executing other work while certain operations are waiting to complete.

Suppose Pradnya starts a timer for two seconds. Node.js does not need to stop all JavaScript execution while the timer is waiting. Other statements can run first.

Event Loop Diagram

1. JavaScript starts an operation
↓
2. Asynchronous work is initiated

For example, a timer or file read

↓
3. Other JavaScript statements can run
↓
4. Callback runs when scheduled

After the operation is ready and its callback can execute

7. Synchronous vs Asynchronous Operations

Synchronous Asynchronous
Waits for an operation to finish before continuing. Allows other work to continue while supported operations are pending.
Can block the JavaScript thread. Can avoid blocking the JavaScript thread while waiting.
Example: readFileSync(). Example: readFile().

Asynchronous does not mean that every operation executes simultaneously. It means the program can coordinate work without waiting synchronously for each operation.

8. Practical Program: Understanding the Event Loop

Samadhan wants to understand why a message outside a timer can appear before the timer's callback.

Step 1: Create a File

Create a file named eventloop.js.

Step 2: Write the Program

JavaScript
console.log("Program started");

setTimeout(() => {
    console.log("Timer completed");
}, 2000);

console.log("Program continues");

Step 3: Run the Program

Terminal
node eventloop.js

Step 4: Expected Output

Output
Program started
Program continues
Timer completed

Step 5: Understand the Output

  1. Program started prints first because it is the first statement.
  2. setTimeout() schedules a callback after a delay of at least approximately two seconds.
  3. JavaScript continues and prints Program continues.
  4. When the timer callback becomes eligible to run, Node.js executes it and prints Timer completed.
Important: The timer delay is not an exact guarantee that the callback executes at precisely two seconds. The callback runs when it is eligible and the event loop can process it.

9. What Is Non-Blocking I/O?

I/O means Input/Output. Examples include reading files, receiving network requests, and sending data.

In non-blocking programming, Node.js can start an asynchronous operation and continue with other JavaScript work rather than waiting synchronously for that operation to finish.

Example: Reading a File

First, create a file named message.txt and write:

Text File
Hello from Samadhan!

Now create fileexample.js in the same folder.

JavaScript
const fs = require("node:fs");

console.log("Reading file...");

fs.readFile("message.txt", "utf8", (err, data) => {
    if (err) {
        console.log("Error reading file");
        return;
    }

    console.log(data);
});

console.log("Other work continues");

Run the Program

Terminal
node fileexample.js

Typical Output

Output
Reading file...
Other work continues
Hello from Samadhan!

Explanation: fs.readFile() starts an asynchronous file read. The next statement can run before the file-read callback. Once the file contents are available, the callback handles the result.

Note: This output order is expected for this example under normal conditions. Callback timing can vary depending on the environment and workload.

10. Does Node.js Use Only One Thread?

Node.js usually executes JavaScript callbacks on one main JavaScript thread per process. However, that does not mean the whole runtime uses only one thread.

  • JavaScript callbacks generally run on the main JavaScript thread.
  • Some file-system, DNS, and other operations can use libuv's worker pool.
  • Networking often relies on operating-system asynchronous facilities.
  • Node.js can also create worker threads or child processes when needed.

This architecture is useful for applications that handle many I/O operations. CPU-heavy JavaScript can still block the main JavaScript thread if it runs for a long time.

Important Points

  • V8 executes JavaScript code.
  • libuv supports the Event Loop and asynchronous I/O.
  • The Event Loop coordinates scheduled callbacks.
  • Non-blocking I/O allows other work to continue while an operation is pending.
  • A timer callback does not necessarily run at its exact requested time.
  • CPU-heavy JavaScript can block the main JavaScript thread.

Summary

Node.js combines the V8 JavaScript engine with runtime APIs and supporting components such as libuv. Its event-driven, non-blocking I/O model helps applications handle asynchronous work efficiently. We also used setTimeout() and fs.readFile() to understand how JavaScript can continue working while an operation is pending.