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 Use Cases

Node.js is used to build web servers, REST APIs, real-time applications, command-line tools, and file-processing systems.

In this lesson, we will understand where Node.js is used in real projects and create practical programs with expected outputs.

1. What Are Node.js Use Cases?

A use case describes a situation where a technology can solve a particular problem.

For example, an online training portal may need to display courses, accept student requests, and send data to a database. Node.js can be used to develop the backend services responsible for these tasks.

Simple definition: A Node.js use case is a type of application or task for which Node.js can be used effectively.

2. Where Is Node.js Used?

Use Case What It Does Example
Web Servers Receives HTTP requests and sends responses. Course website backend.
REST APIs Exchanges data between applications. Student and course API.
Real-Time Applications Supports communication with low delay. Chat and live notifications.
File Processing Reads, writes, and manages files. Reports and document processing.
Command-Line Tools Runs tasks from a terminal. Automation and developer utilities.
Microservices Implements smaller services within a larger system. Authentication or notification service.
Streaming Applications Processes data in manageable chunks. Large file downloads and data pipelines.

3. Use Case: Creating a Web Server

A web server receives requests from a browser and sends responses. Node.js provides the built-in HTTP module for creating servers.

Suppose a training website needs to display a welcome message. We can create a small Node.js server for that purpose.

Step 1: Create server.js

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

const server = http.createServer((req, res) => {
    res.writeHead(200, {
        "Content-Type": "text/plain; charset=utf-8"
    });

    res.end("Welcome to CIIT TRAINING INSTITUTE!");
});

server.listen(3000, () => {
    console.log("Server running at http://localhost:3000");
});

Step 2: Run the Server

Terminal
node server.js

Terminal Output

Output
Server running at http://localhost:3000

Step 3: Open the Browser

Open this address in your browser:

URL
http://localhost:3000

Browser Response

Welcome to CIIT TRAINING INSTITUTE!

Program Explanation

  • require("node:http") imports Node.js's built-in HTTP module.
  • http.createServer() creates an HTTP server.
  • res.writeHead(200, ...) sets the HTTP success status and the response content type.
  • res.end() sends the response and finishes it.
  • server.listen(3000) starts listening on port 3000.
Important: Keep the terminal running while testing the server. If port 3000 is already occupied, choose another available port.

4. Use Case: Building a REST API

A REST API allows applications to exchange data using HTTP. For example, a frontend can request course information from a backend.

The following program creates a simple API using Node.js's built-in HTTP module. It returns course information as JSON.

Step 1: Create api.js

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

const server = http.createServer((req, res) => {
    if (req.url === "/api/course" && req.method === "GET") {
        res.writeHead(200, {
            "Content-Type": "application/json; charset=utf-8"
        });

        res.end(JSON.stringify({
            institute: "CIIT TRAINING INSTITUTE",
            course: "Node.js",
            duration: "Practical learning"
        }));

        return;
    }

    res.writeHead(404, {
        "Content-Type": "application/json; charset=utf-8"
    });

    res.end(JSON.stringify({
        message: "Route not found"
    }));
});

server.listen(3001, () => {
    console.log("API running at http://localhost:3001");
});

Step 2: Run the API

Terminal
node api.js

Step 3: Send a Request

Open this URL in the browser:

URL
http://localhost:3001/api/course

Expected JSON Response

JSON
{
  "institute": "CIIT TRAINING INSTITUTE",
  "course": "Node.js",
  "duration": "Practical learning"
}

Explanation

  • The server checks the request URL and HTTP method.
  • When the URL is /api/course and the method is GET, the server returns course information.
  • JSON.stringify() converts the JavaScript object into JSON text.
  • For an unmatched route, the server returns HTTP status 404.
Real-world note: Production APIs also need validation, authentication where required, error handling, and appropriate security controls.

5. How a Node.js API Works

1. Client Application

Browser or mobile application

↓
2. HTTP Request

Example: GET /api/course

↓
3. Node.js Server

Processes the request

↓
4. HTTP Response

Returns JSON data to the client

6. Use Case: File Processing

Node.js can read and write files using its built-in file-system module. This is useful for processing reports, configuration files, text documents, and application data.

Practical Program

Create a file named file-demo.js.

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

async function main() {
    try {
        await fs.writeFile(
            "training.txt",
            "Welcome to CIIT TRAINING INSTITUTE!"
        );

        const content = await fs.readFile("training.txt", "utf8");

        console.log(content);
    } catch (error) {
        console.error("File operation failed:", error.message);
    }
}

main();

Run the Program

Terminal
node file-demo.js

Expected Output

Output
Welcome to CIIT TRAINING INSTITUTE!

The program also creates a file named training.txt in the current working directory.

Explanation

  • node:fs/promises provides Promise-based file operations.
  • writeFile() creates or replaces the file contents.
  • readFile() reads the saved content.
  • await waits for each Promise inside the asynchronous function.
Important: This example replaces the existing contents of training.txt if that file already exists.

7. Use Case: Real-Time Applications

Node.js is commonly used for applications that need frequent communication between clients and servers.

Examples include:

  • Chat applications.
  • Live notifications.
  • Collaborative tools.
  • Live dashboards and monitoring systems.

Technologies such as WebSocket and Socket.IO can support two-way communication between a client and server.

Example: When a student submits an assignment, a training portal may notify an instructor without requiring the instructor to repeatedly refresh the page.

8. Use Case: Command-Line Applications

Node.js can create programs that run directly in a terminal. These applications are called command-line applications or CLI tools.

Common examples include:

  • File organization utilities.
  • Task management tools.
  • Build and automation scripts.
  • Developer tools for checking or processing data.

Simple CLI Program

Create cli.js.

JavaScript
const task = process.argv[2];

if (!task) {
    console.log("Usage: node cli.js <task>");
} else {
    console.log("Task received:", task);
}

Run the Program

Terminal
node cli.js "Complete Node.js lesson"

Expected Output

Output
Task received: Complete Node.js lesson

Explanation

process.argv contains command-line arguments. In this example, process.argv[2] reads the first argument provided after the JavaScript filename.

9. Use Case: Microservices

A microservices architecture divides an application into smaller services that communicate through defined interfaces. Node.js can be used to implement these services.

For example, an online learning platform might have separate services for student accounts, courses, notifications, and reports.

Training Portal
↓
Student Service

Accounts and profiles

Course Service

Course information

Notification Service

Messages and alerts

This is an example architecture. A real microservices system requires service communication, monitoring, deployment, and security.

10. Advantages of Using Node.js

  • Supports backend development using JavaScript.
  • Provides APIs for HTTP, file operations, and other tasks.
  • Supports asynchronous I/O for many I/O-heavy applications.
  • Provides an ecosystem of reusable packages through npm.
  • Can be used for APIs, real-time applications, and CLI tools.

11. When Should We Be Careful?

Node.js is not automatically the best choice for every workload. Technology selection should depend on the application requirements.

  • Long-running CPU-heavy JavaScript can block the main thread.
  • Applications need suitable error handling and input validation.
  • Database access and external services can still become bottlenecks.
  • Security, logging, testing, and deployment need careful planning.

Node.js Learning at CIIT TRAINING INSTITUTE

At CIIT TRAINING INSTITUTE, these use cases can be practised step by step, from basic JavaScript programs to complete backend applications.

Practical Learning Areas
  • Create an HTTP server.
  • Develop REST API endpoints.
  • Read and write files using Node.js.
  • Build command-line utilities.
  • Understand real-time communication.
  • Learn how backend services fit into larger applications.

These exercises help learners build practical skills that can be extended to database integration, authentication, testing, and project development.

Important Points

  • Node.js can create HTTP servers and REST APIs.
  • It supports asynchronous file processing.
  • It can be used for real-time applications and CLI tools.
  • Node.js can implement microservices.
  • Choose the technology according to the workload and project requirements.

Summary

Node.js is useful for web servers, REST APIs, file processing, real-time communication, command-line applications, and microservices. Its asynchronous APIs can help applications handle I/O efficiently. Practical exercises at CIIT TRAINING INSTITUTE can help students build a foundation for developing backend applications and understanding real-world systems.