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

Asynchronous Programming in Node.js

Learn how asynchronous programming works in Node.js, how non-blocking operations improve application responsiveness, and how callbacks, Promises, and async/await handle asynchronous tasks.

In the previous module, we learned about events and EventEmitter. Now, we will explore asynchronous programming in Node.js. Asynchronous programming allows an application to start an operation and continue executing other code while waiting for that operation to complete.

Throughout this module, we will use examples from CIIT Training Institute. Samadhan and Pradnya will help us understand how an application can handle student enquiries, course information, and other tasks without unnecessarily blocking execution.

1. What Is Asynchronous Programming?

Asynchronous programming is a programming approach in which certain operations can complete later without requiring the rest of the program to wait synchronously for their results.

For example, when Samadhan requests student information from a database, the application may need to wait for the database response. With asynchronous APIs, Node.js can continue handling other work while the operation is in progress.

When the result becomes available, the application can process it using a callback, a Promise, or async/await.

Remember: Asynchronous programming helps manage operations that take time to complete. It does not mean that every operation runs simultaneously or that JavaScript automatically creates a new thread.

2. Synchronous vs Asynchronous Programming

In synchronous execution, the next statement generally waits for the current operation to finish. With asynchronous APIs, an operation can complete later while other eligible code runs.

Feature Synchronous Asynchronous
Execution Statements proceed after the current operation finishes. Some operations complete later.
Waiting A blocking operation can prevent further execution. Non-blocking operations allow other work to proceed.
Result handling The result is available before execution continues. The result is handled later using an asynchronous mechanism.
Node.js example readFileSync() readFile() with a callback.

3. Example of Synchronous Execution

First, let's understand a simple synchronous program. Each statement executes in sequence.

Program

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

console.log("Pradnya is checking course details.");

console.log("Task completed.");

Expected Output

Output
Samadhan started the task.
Pradnya is checking course details.
Task completed.

Each console.log() statement executes in order. This example is synchronous because no asynchronous operation is involved.

4. Example of Asynchronous Execution

Node.js provides functions such as setTimeout() that schedule a callback to run later. This helps demonstrate how execution can continue before a scheduled callback runs.

Program

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

setTimeout(() => {
    console.log("Pradnya finished checking course details.");
}, 2000);

console.log("Samadhan continues other work.");

Expected Output

Output
Samadhan started the task.
Samadhan continues other work.
Pradnya finished checking course details.

The callback passed to setTimeout() is scheduled to run after at least approximately two seconds. Meanwhile, the next synchronous statement executes.

Key Learning: Samadhan does not have to wait for the scheduled callback before executing the next statement.

5. Asynchronous Execution Flow

This diagram shows how Node.js can continue executing synchronous code while a callback is waiting to run.

1. Start Program

Samadhan starts the task.

↓
2. Schedule Asynchronous Work

setTimeout(callback, 2000)

↓
3. Continue Synchronous Code

Samadhan continues other work.

↓
4. Execute Scheduled Callback

Pradnya's completion message appears.

Note: The delay specifies a minimum scheduling threshold, not an exact execution time. The callback runs when the event loop can process it.

6. Why Is Asynchronous Programming Important in Node.js?

Node.js is commonly used for applications that handle network requests, file operations, database queries, and other input/output tasks. Non-blocking APIs help an application remain responsive while these operations are in progress.

Operation Example at CIIT Training Institute Possible Benefit
File operations Reading course information from a file. Other work can continue while asynchronous file I/O is pending.
Database operations Retrieving student enquiry details. Requests can be handled without synchronously waiting for every query.
HTTP requests Serving multiple student enquiries. Non-blocking I/O supports responsive request handling.
Timers Scheduling a delayed notification. Other eligible code can run while the timer is pending.

7. Common Asynchronous Programming Patterns

JavaScript and Node.js provide several ways to handle asynchronous results. We will study each approach in detail in the upcoming lessons.

Pattern How It Works Common Example
Callbacks A function is passed to be called later. fs.readFile()
Promises Represent the eventual success or failure of an operation. fetch()
async/await Provides syntax for working with Promises. await fetch(url)
Timers Schedule callbacks for later execution. setTimeout()

8. Introduction to Callbacks

A callback is a function passed as an argument to another function. The receiving function can call that callback when a particular task or condition is reached.

Callbacks can be synchronous or asynchronous. In Node.js, callback functions are commonly used to process the result of asynchronous operations.

Example

JavaScript
function greetStudent(name, callback) {
    console.log("Welcome, " + name);

    callback();
}

function showInstitute() {
    console.log("Welcome to CIIT Training Institute!");
}

greetStudent("Pradnya", showInstitute);

Expected Output

Output
Welcome, Pradnya
Welcome to CIIT Training Institute!

In this example, showInstitute is passed as a callback function. The greetStudent() function invokes it after displaying the student's name.

Important: This particular callback is executed synchronously. A callback is not automatically asynchronous just because it is called a callback.

9. Asynchronous Programming Concepts Diagram

This diagram summarizes the main patterns we will learn throughout the asynchronous programming module.

Asynchronous Operation

Example: Read course information

↓
Callbacks

Handle a result through a function.

Promises

Represent a future result or failure.

async/await

Work with Promises using readable syntax.

Important Points

  • Asynchronous programming allows certain operations to complete later.
  • Non-blocking operations allow other eligible work to proceed while I/O is pending.
  • Node.js provides callback-based and Promise-based APIs.
  • async/await provides syntax for working with Promises.
  • Callbacks can be synchronous or asynchronous.
  • setTimeout() schedules a callback; it does not guarantee execution at an exact time.

Summary

In this lesson, we introduced asynchronous programming in Node.js and compared synchronous and asynchronous execution. We learned how scheduled callbacks allow synchronous code to continue, explored why non-blocking I/O matters, and introduced callbacks, Promises, and async/await. In the next lesson, we will study callbacks in more detail using practical JavaScript examples.