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

CommonJS Modules in Node.js

Learn how to export and import functions, variables and objects using the CommonJS module system in Node.js.

require() module.exports exports Custom Modules Code Reusability

1. What Is CommonJS?

CommonJS is a module system traditionally used by Node.js to organize JavaScript code into separate files. It allows one file to expose functionality and another file to load and use that functionality.

For example, suppose an application needs addition, subtraction, multiplication and division operations. We can write these functions in a separate calculator module and reuse them in other files.

CommonJS primarily uses two mechanisms:

  • module.exports: Exposes values or functionality from a module.
  • require(): Loads the exported value from another module.
Definition: CommonJS is a module system that lets Node.js files share functionality using exports and require.

2. Why Do We Use CommonJS Modules?

CommonJS helps developers organize code so that each file can handle a particular responsibility.

  • Reusability: Use the same function in multiple files.
  • Organization: Keep related logic together.
  • Maintainability: Update a module without duplicating its code.
  • Readability: Make large applications easier to understand.
  • Separation of Responsibilities: Separate calculation, validation and other tasks.

3. How CommonJS Works

A CommonJS module exports a value, and another file loads that value using require().

Step 1: Create

math.js

Define the reusable function.

function add(a, b) { ... }
↓
Step 2: Export

module.exports

Expose the function to other files.

module.exports = add;
↓
Step 3: Import

app.js

Load the exported function.

const add = require("./math");
↓
Step 4: Execute

Use the Function

add(10, 20)

Result: 30

4. Understanding module.exports

The module.exports object determines what a CommonJS module makes available to other files.

You can export a function, an object, an array or another value. The importing file receives that exported value from require().

Example: Export a Single Function

Create a file named greeting.js.

greeting.js
function greet() {
    return "Welcome to Node.js!";
}

module.exports = greet;

Now create app.js to use the function.

app.js
const greet = require("./greeting");

console.log(greet());

Expected Output

Welcome to Node.js!

Explanation

  1. The greet() function is defined in greeting.js.
  2. module.exports = greet exposes the function.
  3. require("./greeting") loads the exported function.
  4. greet() calls the function and returns the message.
  5. console.log() displays the returned message.

5. Export Multiple Functions

A module can expose multiple functions through an object. This is useful when several operations belong to the same feature.

Step 1: Create calculator.js

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

function subtract(a, b) {
    return a - b;
}

function multiply(a, b) {
    return a * b;
}

module.exports = {
    add,
    subtract,
    multiply
};

Step 2: Use the Functions in app.js

app.js
const calculator = require("./calculator");

console.log("Addition:", calculator.add(20, 10));
console.log("Subtraction:", calculator.subtract(20, 10));
console.log("Multiplication:", calculator.multiply(20, 10));

Expected Output

Addition: 30
Subtraction: 10
Multiplication: 200

The imported calculator variable refers to the object exported by calculator.js. Its methods are accessed using dot notation.

6. Destructuring Imported Functions

Instead of accessing every function through the module object, we can use object destructuring to extract the required functions.

app.js
const { add, subtract } = require("./calculator");

console.log(add(15, 5));
console.log(subtract(15, 5));

Expected Output

20
10

Here, add and subtract are extracted from the object returned by require("./calculator").

Remember: The names used in the destructuring pattern must match the corresponding exported property names, unless you explicitly rename them.

7. Understanding exports

Node.js also provides an exports shortcut that initially refers to the same object as module.exports. You can attach properties to it to expose multiple values.

Example

calculator.js
exports.add = function(a, b) {
    return a + b;
};

exports.multiply = function(a, b) {
    return a * b;
};

Import the exported functions in app.js.

app.js
const calculator = require("./calculator");

console.log(calculator.add(5, 3));
console.log(calculator.multiply(5, 3));

Expected Output

8
15
Important: Do not replace exports directly with a new value. For example, exports = function() {} does not replace module.exports. Use module.exports = ... when exporting a single function or a completely new value.

8. module.exports vs exports

Feature module.exports exports
Purpose Defines the value exported by the module. Shortcut for adding properties to the initial export object.
Export a single function module.exports = greet; Not by reassigning exports directly.
Export multiple properties module.exports = { add, subtract }; exports.add = add;
Can replace the exported value? Yes. Reassigning the local exports variable does not replace the exported value.

9. How Multiple Exports Work

When multiple functions are exported as object properties, the importing file can access each function using its property name.

calculator.js

Create Functions

add(), subtract(), multiply()
↓
Export an Object

module.exports

{ add, subtract, multiply }
↓
Load the Module

app.js

const calculator = require("./calculator");
↓
Use Required Functions

Call the Methods

calculator.add(20, 10)

Result: 30

10. Practical Example: Student Module

Consider a student management application. We can place student-related functionality in a separate module and use it in the main application.

Step 1: Create student.js

student.js
function getStudentDetails(name, course) {
    return {
        name: name,
        course: course
    };
}

module.exports = getStudentDetails;

Step 2: Create app.js

app.js
const getStudentDetails = require("./student");

const student = getStudentDetails("Samadhan", "Node.js");

console.log("Student:", student.name);
console.log("Course:", student.course);

Expected Output

Student: Samadhan
Course: Node.js

Explanation

  1. The student module defines a function that creates a student object.
  2. The function is exported using module.exports.
  3. The main file loads the function using require().
  4. The function receives a student name and course name.
  5. The returned object is used to display the student's details.

11. How to Run a CommonJS Program

Save the example files in the same folder. For example:

Project Structure
CommonJSExample/
    app.js
    calculator.js
    student.js

Open a terminal in the project folder and execute:

Terminal
node app.js

Node.js executes app.js, loads the required local modules and displays the output.

Check before running: Ensure Node.js is installed, the terminal is opened in the correct folder, and the filenames in the require() statements match your actual files.

12. Common Mistakes

Mistake Correct Approach
Forgetting to export a function. Expose it using module.exports or a property on exports.
Using an incorrect module path. Verify the relative path and filename.
Calling a method that was not exported. Check the names of exported properties.
Writing exports = value to replace the module export. Assign the value to module.exports.
Mixing CommonJS with ES Module syntax without checking configuration. Confirm which module system the file uses.

13. Practice Tasks

Task 1: Create a Calculator Module

Create a file named calculator.js. Add functions for addition, subtraction and multiplication. Export all three functions and use them from app.js.

Expected Output:
Addition: 30
Subtraction: 10
Multiplication: 200

Task 2: Create a Student Module

Create a function that accepts a student name and course, returns an object, and exports the function. Import it in another file and display the details.

Expected Output:
Student: Pradnya
Course: JavaScript

Task 3: Export Multiple Values

Create a module that exports a constant named instituteName and a function named getWelcomeMessage(). Import both in another file and display their values.

Summary

CommonJS is a module system traditionally used in Node.js to organize JavaScript code into reusable files. The module.exports property exposes functions, objects, and other values, while require() loads those exported values into another file. The exports shortcut can add properties to the module's export object, but assigning a new value directly to exports does not replace module.exports. CommonJS modules improve code reusability, readability, maintainability, and separation of responsibilities in Node.js applications.