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 Built-in Modules

Learn how Node.js built-in modules provide functionality for file handling, path operations, operating-system information, HTTP servers, events and URL processing.

fs path os http events url

1. What Are Built-in Modules?

Built-in modules are modules provided by Node.js itself. They provide functionality for common programming tasks without requiring us to install a separate package for each feature.

For example, when an application needs to read a file, it can use the fs module. When it needs to work with file paths, it can use the path module. A server can use the http module to receive requests and send responses.

Definition: A built-in module is functionality supplied by Node.js that can be loaded and used directly in a Node.js application.

Advantages of Built-in Modules

  • No separate package installation is required for these modules.
  • They provide ready-to-use functionality.
  • They reduce the amount of code we need to write ourselves.
  • They help developers work with files, operating-system information and networking.

2. Common Built-in Modules

Module Purpose Example Use
fs File system operations Read or write a file
path File and directory paths Join path segments
os Operating-system information Get platform or CPU information
http HTTP server functionality Receive HTTP requests
events Event-driven programming Emit and handle custom events
url URL processing Read URL pathname or query parameters

3. How Built-in Modules Work

A Node.js application imports the required built-in module, calls its methods and uses the returned values or results.

Step 1

Node.js Application

Identify the required functionality.

↓
Step 2

Import Built-in Module

const path = require("node:path");
↓
Step 3

Call a Module Method

path.join("folder", "file.txt");
↓
Step 4

Use the Result

The application receives the resulting path.

4. fs Module — File System

The fs module allows a Node.js application to interact with the file system. It supports operations such as reading, writing, appending and deleting files.

Example: Write a File

The writeFileSync() method writes content to a file synchronously. If the file does not exist, it normally creates it. If it already exists, its contents are replaced.

app.js - CommonJS
const fs = require("node:fs");

fs.writeFileSync("message.txt", "Welcome to Node.js!");

console.log("File created successfully.");

Expected Output

File created successfully.

A file named message.txt is created in the current working directory if it does not already exist. Its content is:

message.txt
Welcome to Node.js!

Example: Read a File

app.js
const fs = require("node:fs");

const content = fs.readFileSync("message.txt", "utf8");

console.log(content);

Expected Output

Welcome to Node.js!
Important: Synchronous file operations block further JavaScript execution on the current thread until the operation finishes. For many application workflows, asynchronous methods such as fs.readFile() are preferable.

5. path Module — File Paths

The path module provides utilities for working with file and directory paths. It helps build paths using the correct separators for the operating system.

Example: Join Path Segments

app.js
const path = require("node:path");

const filePath = path.join("students", "details", "student.txt");

console.log(filePath);

Expected Output on Windows

students\details\student.txt

Example: Get File Extension

app.js
const path = require("node:path");

const fileName = "student.js";

console.log(path.extname(fileName));

Expected Output

.js

The exact path separator depends on the operating system. path.join() builds a path using the platform's normal separator.

6. os Module — Operating System

The os module provides information about the operating system on which Node.js is running.

Example: Get Platform and Architecture

app.js
const os = require("node:os");

console.log("Platform:", os.platform());
console.log("Architecture:", os.arch());

Example Output on a Typical 64-bit Windows Computer

Platform: win32
Architecture: x64

The actual output depends on the computer running the program. Other operating systems can return different platform values.

Example: Get CPU Information

app.js
const os = require("node:os");

console.log("CPU Information:");
console.log(os.cpus());

The output contains CPU details and can be lengthy because it depends on the machine's processor configuration.

7. http Module — Create a Server

The http module provides functionality for creating HTTP servers. A server can receive requests and send responses to clients.

Example: Create a Simple HTTP Server

server.js
const http = require("node:http");

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

    res.end("Welcome to Node.js Server!");
});

server.listen(3000, () => {
    console.log("Server is running on port 3000.");
});

Expected Terminal Output

Server is running on port 3000.

Response Body

Welcome to Node.js Server!

Save the code in server.js and run it using node server.js. The server listens on port 3000. A client can then send a request to the server on that port.

Important: Keep the server process running while testing it. Stop it using Ctrl + C in the terminal when you finish.

8. events Module — Event Handling

Node.js uses an event-driven programming model. The events module provides the EventEmitter class, which lets us define and handle custom events.

Example: Create a Custom Event

app.js
const EventEmitter = require("node:events");

const eventEmitter = new EventEmitter();

eventEmitter.on("welcome", () => {
    console.log("Welcome event executed!");
});

eventEmitter.emit("welcome");

Expected Output

Welcome event executed!

Explanation

  1. EventEmitter is imported from the built-in module.
  2. An event emitter object is created.
  3. on() registers a listener for the welcome event.
  4. emit() triggers that event.
  5. The registered callback displays the message.

9. url Module — URL Processing

The URL class allows us to parse and work with URLs, including their hostnames, pathnames and query parameters.

Example: Read URL Information

app.js
const { URL } = require("node:url");

const myUrl = new URL(
    "https://example.com/students?course=nodejs"
);

console.log("Hostname:", myUrl.hostname);
console.log("Pathname:", myUrl.pathname);
console.log("Course:", myUrl.searchParams.get("course"));

Expected Output

Hostname: example.com
Pathname: /students
Course: nodejs

The URL is parsed as data; this example does not send a network request to the host.

10. Built-in Modules in an Application

Different modules can support different parts of the same Node.js application. The application selects the module that matches the task it needs to perform.

Application

Node.js Program

Choose the required operation.

↓
File Operations

fs

Read and write files.

Path Operations

path

Build and inspect paths.

System Information

os

Inspect the host system.

Web Server

http

Handle HTTP requests.

Custom Events

events

Register and emit events.

URL Processing

url

Read URL components.

↓
Application Result

The selected module provides the required functionality.

11. CommonJS and ES Module Import Syntax

Built-in modules can be used with CommonJS or ES Module syntax, depending on how the application is configured.

Module CommonJS ES Modules
File system const fs = require("node:fs"); import fs from "node:fs";
Path const path = require("node:path"); import path from "node:path";
Operating system const os = require("node:os"); import os from "node:os";
HTTP const http = require("node:http"); import http from "node:http";
Tip: The node: prefix explicitly identifies a Node.js built-in module. It can be used with built-in module imports in supported Node.js versions.

12. Common Mistakes

Mistake Correct Approach
Trying to install a built-in module separately. Use the built-in module supplied by Node.js.
Using an incorrect import syntax. Check whether the file uses CommonJS or ES Modules.
Reading a file that does not exist. Ensure the file exists at the expected location and handle errors.
Assuming every operating system produces identical output. Remember that path and OS information can vary by platform.
Assuming an HTTP server stops automatically. Keep the server running during testing and stop it when finished.

13. Practice Tasks

Task 1: File System

Use the fs module to create a file named student.txt, write a student name into it, and read the content.

Expected Output:
Student file created.
Student: Samadhan

Task 2: Path Module

Use the path module to join a folder name with a filename and display the file extension.

Expected Extension:
.js

Task 3: Events Module

Create a custom event named studentRegistered. Register an event listener and emit the event.

Expected Output:
Student registered successfully!

Task 4: Operating System

Use the os module to display the operating-system platform and CPU architecture of your computer.

Summary

Node.js built-in modules provide ready-to-use functionality for common application tasks. The fs module handles file operations, path manages file paths, os provides operating-system information, http supports HTTP servers, events enables custom event handling, and url helps process URL components. These modules can be imported using CommonJS or ES Module syntax, depending on the project configuration. Understanding built-in modules helps developers build organized Node.js applications without installing separate packages for these core features.