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

Introduction to Node.js Modules

Understand what modules are in Node.js, why we use them, how modules organize application code, and how different JavaScript files can share functionality.

Modules Code Reusability CommonJS ES Modules Built-in Modules

1. What Are Modules in Node.js?

A module is a reusable unit of code that contains related functions, variables, classes, or other functionality. Modules help us divide a large application into smaller, manageable files.

Imagine developing a student management application. The application may need to manage student details, calculate fees, validate data, and generate reports. Instead of writing everything in one file, we can organize these responsibilities into separate modules.

For example:

  • student.js can contain student-related functions.
  • fees.js can contain fee calculation functions.
  • validation.js can contain validation logic.
  • app.js can coordinate the application's operations.
Definition: A Node.js module is a reusable unit of code that can organize functionality and, when needed, expose values or functions for use by other modules.

2. Why Do We Need Modules?

When an application grows, maintaining all its code in a single file becomes difficult. Modules allow developers to separate responsibilities and work with smaller pieces of code.

Advantages of Modules

  • Code Reusability: A function can be shared with other files instead of being rewritten.
  • Better Organization: Related functionality can be grouped into separate files.
  • Easy Maintenance: A specific feature can be updated without searching through one large file.
  • Readability: Smaller files make the application easier to understand.
  • Team Collaboration: Developers can work on different modules independently.
  • Separation of Responsibilities: Each module can focus on a particular task.

3. Node.js Module Architecture

In a modular application, different files handle different responsibilities. The main application imports or loads the required functionality and uses it when needed.

Main Application

app.js

Coordinates the application and uses required modules.

↓
student.js

Student information and operations

fees.js

Fee calculations

validation.js

Data validation

Each module manages its own responsibility and exposes functionality that other files may use.

This structure makes it easier to understand which file is responsible for a particular task. The exact way functionality is shared depends on the module system being used.

4. Types of Modules in Node.js

Node.js applications commonly use three categories of modules: built-in modules, custom modules, and third-party modules.

Module Type Description Examples
Built-in Modules Modules supplied by Node.js. fs, path, os, http
Custom Modules Modules created by developers for their applications. student.js, fees.js
Third-party Modules Packages created and distributed by other developers. express, mongoose
Remember: Built-in modules are supplied with Node.js. Third-party packages are added to a project when needed, commonly with a package manager such as npm.

5. CommonJS Module System

CommonJS is a module system traditionally used by Node.js. It commonly uses require() to load a module and module.exports or exports to expose functionality.

Example: Export a Function

Create a file named math.js and define an addition function inside it.

math.js
function add(a, b) {
    return a + b;
}

module.exports = add;

Import and Use the Function

Create another file named app.js. Load the exported function using require().

app.js
const add = require("./math");

const result = add(10, 20);

console.log("Addition:", result);

Expected Output

Addition: 30

Explanation

  1. math.js defines the add() function.
  2. module.exports = add exposes that function.
  3. require("./math") loads the exported value.
  4. add(10, 20) executes the imported function.
  5. The result is displayed using console.log().

6. ES Modules

ES Modules (ESM) are the standard JavaScript module system. They use the export keyword to expose functionality and the import keyword to use exported functionality.

Export a Function

math.mjs
export function add(a, b) {
    return a + b;
}

Import and Use the Function

app.mjs
import { add } from "./math.mjs";

console.log("Addition:", add(15, 25));

Expected Output

Addition: 40

These examples use the .mjs extension to identify ES modules explicitly. Node.js also supports ES modules in appropriately configured .js files.

Key Difference: CommonJS commonly uses require() and module.exports, whereas ES Modules use import and export.

7. How Import and Export Work

Exporting makes functionality available to another module. Importing or requiring loads that functionality so the current file can use it.

File 1

math.js

function add(a, b)

Defines the function.

↓
Export

Expose Functionality

module.exports = add

Makes the function available to another CommonJS module.

↓
Import

app.js

const add = require("./math")

Loads the exported function.

↓
Execution

Use the Function

add(10, 20)

The result is 30.

This diagram illustrates the CommonJS approach. ES Modules use the same general idea of sharing functionality, but use export and import syntax.

8. CommonJS vs ES Modules

Feature CommonJS ES Modules
Load or import require() import
Export module.exports or exports export or export default
Typical file extension .cjs or CommonJS-configured .js .mjs or ES-module-configured .js
Module style CommonJS module system Standard JavaScript module system
Example const fs = require("node:fs") import fs from "node:fs"
Important: Use a consistent module system for your files and understand how your project's configuration determines whether a file is treated as CommonJS or an ES module.

9. Built-in Modules Overview

Node.js provides built-in modules for common tasks. These modules can be used without separately installing a package.

Module Purpose
fs Work with files and directories.
path Work with file and directory paths.
os Access operating-system information.
http Create HTTP servers and handle HTTP requests.
events Work with event-driven programming.
url Parse and work with URL information.

These modules will be covered individually in upcoming Node.js tutorial topics.

10. Common Mistakes

Mistake Correct Understanding
Trying to import a function that was not exported. Ensure the required function or value is exported.
Using the wrong file path. Check the relative path and filename.
Mixing CommonJS and ES Module syntax without understanding the configuration. Check the module system used by the project.
Assuming every module must be installed separately. Node.js already provides built-in modules.
Writing all application logic in a single file. Separate related responsibilities into modules when appropriate.

11. Practice Tasks

Task 1: Create a Calculator Module

Create calculator.js and define functions for addition and subtraction. Export the functions and use them in app.js.

Expected Results:
Addition: 30
Subtraction: 10

Task 2: Create a Student Module

Create a module that exports a function returning a student's name and course. Import the function into another file and display the result.

Expected Output:
Student: Samadhan
Course: Node.js

Task 3: Try ES Modules

Create a module that exports a multiplication function using export. Import it into another ES module using import.

Expected Output:
Multiplication: 200

Summary

Node.js modules organize application code into reusable and manageable units. Built-in modules provide functionality for common tasks, custom modules allow developers to separate their own application logic, and third-party modules provide additional features. CommonJS uses require() and module.exports to load and share functionality, while ES Modules use import and export. Using modules improves code reusability, readability, maintainability, and application organization.