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

Event Loop and Non-Blocking I/O in Node.js

Node.js uses an event loop to coordinate JavaScript execution, asynchronous callbacks, timers, and I/O operations. Non-blocking I/O allows Node.js to continue processing other work while waiting for operations such as file access or network communication.


1. What is the Event Loop?

The event loop is a mechanism used by Node.js to process scheduled callbacks and coordinate asynchronous operations. It helps Node.js handle many I/O operations without waiting synchronously for each operation to finish.

Imagine Samadhan is working on a project at CIIT Training Institute. He asks Pradnya to fetch a course report. While the report is being prepared, Samadhan can continue other work instead of waiting idle. Node.js follows a similar idea when handling asynchronous I/O.

Simple Trick: The event loop helps Node.js decide which scheduled callback can run next. Non-blocking I/O allows other work to continue while an I/O operation is waiting.

2. Why Do We Need the Event Loop?

Consider a program that needs to read a file and then display another message. If the program uses synchronous file reading, JavaScript execution waits until the file read completes. With asynchronous file reading, the program can continue executing other statements.

Blocking Operation Non-Blocking Operation
The current JavaScript execution waits for the operation to finish. The operation can proceed asynchronously while JavaScript continues with other work.
Can delay other work on the same JavaScript thread. Helps the application remain responsive during I/O.
Example: readFileSync(). Example: readFile() with a callback.

3. Event Loop Architecture

Node.js executes JavaScript on its main thread by default. Its runtime coordinates timers, I/O completion, and callbacks. Some operations use operating-system facilities or the libuv thread pool.

Simplified Node.js Event Loop Diagram
JavaScript Code
Runs on the main JavaScript thread.
↓
Asynchronous Operation
Timer, file I/O, network I/O, or another supported task.
↓
Operation Completes
The runtime makes the associated callback eligible to run.
↓
Event Loop
Coordinates eligible callbacks and scheduled work.
↓
Callback Executes
When the JavaScript thread can process it.

4. Synchronous Code Example

Synchronous statements execute in order. Each statement completes before the next statement starts.

JavaScript
console.log("Samadhan started.");

console.log("Pradnya is preparing the report.");

console.log("Samadhan continues the next task.");
Output
Samadhan started.
Pradnya is preparing the report.
Samadhan continues the next task.
Explanation
  • The first statement displays the starting message.
  • The second statement executes next.
  • The third statement executes after the second statement finishes.
  • No asynchronous operation is scheduled in this example.

5. Non-Blocking Execution Example

The following example uses setTimeout() to schedule a callback. JavaScript continues executing the remaining statement without waiting for the timer.

JavaScript
console.log("Samadhan started.");

setTimeout(() => {
    console.log("Pradnya's report is ready.");
}, 2000);

console.log("Samadhan continues working.");
Output
Samadhan started.
Samadhan continues working.
Pradnya's report is ready.
The last message is scheduled after approximately two seconds.
Explanation
  1. The first message is displayed immediately.
  2. setTimeout() schedules the callback.
  3. The next statement executes without waiting for the timer.
  4. When the timer expires, the callback becomes eligible to run.
  5. The event loop processes the callback when JavaScript can execute it.

6. How the Event Loop Works

Execution Flow Diagram
1. Execute Synchronous Code
JavaScript runs the current statements.
↓
2. Schedule Asynchronous Work
Timers and I/O operations are registered with the runtime.
↓
3. Continue Other Work
JavaScript can execute other available statements.
↓
4. Process Scheduled Callbacks
The runtime coordinates callbacks as they become eligible.
↓
5. Application Continues
More callbacks and operations can be processed.

7. Non-Blocking I/O Using the File System

Node.js provides the fs module for working with files. The asynchronous fs.readFile() method allows the program to continue executing while the file is being read.

Before running this example: Create a file named course.txt in the same directory from which the Node.js script is run, and put Welcome to CIIT Training Institute! inside it.
JavaScript
const fs = require("fs");

console.log("Samadhan started reading the course file.");

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

    console.log("File content:", data);
});

console.log("Samadhan can do other work while the file is read.");
Possible Output
Samadhan started reading the course file.
Samadhan can do other work while the file is read.
File content: Welcome to CIIT Training Institute!

The file callback normally runs after the synchronous statements shown here. Actual completion time depends on the file system and runtime.

Explanation
  • require("fs") imports Node.js file-system functions.
  • fs.readFile() requests an asynchronous file read.
  • The callback receives an error or the file data.
  • The next console.log() can run while the file read is pending.
  • The error check prevents the program from trying to use data when the read fails.

8. Event Loop Phases in Node.js

Node.js organizes many callback operations into event loop phases. These phases help the runtime process different categories of work.

Phase Purpose
Timers Processes eligible callbacks scheduled by functions such as setTimeout() and setInterval().
Pending Callbacks Processes certain system-level callbacks deferred to this phase.
Idle / Prepare Internal work performed by the runtime.
Poll Processes many I/O callbacks and may wait for I/O when appropriate.
Check Processes callbacks scheduled using setImmediate().
Close Callbacks Processes certain close events, such as a socket closing.
Note: Promise callbacks and process.nextTick() are handled through their respective queues and scheduling rules, rather than being ordinary event loop phases in this table. Exact scheduling behavior can depend on the Node.js version and execution context.

9. What is Blocking Code?

Blocking code prevents the JavaScript thread from executing other JavaScript while the blocking operation is running. Long-running synchronous work can delay timers, I/O callbacks, and other requests.

JavaScript
const fs = require("fs");

console.log("Samadhan started.");

try {
    const data = fs.readFileSync("course.txt", "utf8");
    console.log("File content:", data);
} catch (error) {
    console.log("Error reading file:", error.message);
}

console.log("Samadhan continues after the file read.");
Execution Order
Samadhan started.
File content: Welcome to CIIT Training Institute!
Samadhan continues after the file read.
This output assumes course.txt exists and contains the example text.

Unlike fs.readFile(), fs.readFileSync() does not return control to the next statement until the file read completes or fails.

10. Blocking vs Non-Blocking I/O

Blocking I/O Non-Blocking I/O
Waits for the operation to complete before continuing. Allows JavaScript to continue while the operation is pending.
Can delay other work on the same JavaScript thread. Can improve responsiveness when waiting for I/O.
Example: fs.readFileSync(). Example: fs.readFile().
Useful when synchronous behavior is specifically needed. Often preferred for server applications handling concurrent I/O.

11. Common Mistakes

Mistake Correct Understanding
Assuming asynchronous callbacks execute immediately. Callbacks run when they become eligible and the runtime can process them.
Assuming a timer always executes at the exact delay. The specified delay is not a guarantee of exact execution time.
Using synchronous I/O for every file operation in a server. Consider asynchronous I/O when the application should continue handling other work.
Assuming Node.js never uses threads. Node.js can use operating-system facilities and the libuv thread pool for certain operations.
Writing long-running CPU-heavy code on the main JavaScript thread. Consider worker threads or other suitable approaches for CPU-intensive tasks.

12. Important Points to Remember

  • The event loop coordinates scheduled callbacks and asynchronous work.
  • Non-blocking I/O allows JavaScript to continue while I/O is pending.
  • Synchronous operations execute before the next statement can proceed.
  • Asynchronous operations may complete later and schedule callbacks.
  • Node.js has event loop phases for different categories of callbacks.
  • Long-running synchronous code can block the main JavaScript thread.
  • Node.js uses runtime and operating-system facilities to support asynchronous I/O.

Summary

In this lesson, we learned about the Node.js event loop, non-blocking I/O, synchronous and asynchronous execution, file-system examples, event loop phases, and blocking code. The examples involving Samadhan, Pradnya, and CIIT Training Institute demonstrate how Node.js can continue executing work while asynchronous operations are pending.