Lesson 8 of 50 – CommonJS Modules
16% Completed
16%

Node.js CommonJS Modules

CommonJS is a module system used in Node.js. It allows us to divide a large program into smaller files and share functions, variables, objects, and other code between them.

In simple words: CommonJS allows one JavaScript file to export code and another JavaScript file to import and use it.

1. What Is CommonJS?

CommonJS is a traditional module system supported by Node.js. It commonly uses two important features:

  • require() – loads a module.
  • module.exports – exports values from a file.
Example: Loading a Built-in Module
const os = require('node:os');

console.log(os.platform());
console.log(os.arch());

The require() function loads Node.js's built-in OS module. The module provides information about the operating system.

2. Understanding require()

The require() function loads a module so that its exported values can be used in the current file.

Example: Using the Path Module
const path = require('node:path');

const filePath = path.join('students', 'data.txt');

console.log(filePath);

Possible output on Windows:

students\data.txt

The path module helps us work with file and directory paths. The exact path separator depends on the operating system.

3. Creating Your Own Module

We can create our own JavaScript file and export a function from it. Another file can then import that function using require().

Step 1: Create math.js
function add(a, b) {
    return a + b;
}

module.exports = add;

Here, module.exports = add; exports the add() function from this file.

Step 2: Create app.js
const add = require('./math');

console.log(add(10, 20));

Output:

30

The ./math path refers to the local math.js file. Node.js can resolve the .js extension automatically in this case.

4. Exporting Multiple Functions

We can export multiple functions by placing them inside an object.

Step 1: Create 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 calculator.js
const calculator = require('./calculator');

console.log(calculator.add(10, 5));
console.log(calculator.subtract(10, 5));
console.log(calculator.multiply(10, 5));

Output:

15
5
50

5. What Is exports?

Node.js also provides an exports shortcut that initially refers to the same export object as module.exports. We can use it to add properties to that object.

Example: Using exports
exports.name = 'Rahul';
exports.age = 20;

In another file:

const student = require('./student');

console.log(student.name);
console.log(student.age);

Output:

Rahul
20
Important: Use module.exports = value when exporting a single function or replacing the entire exported value. Do not assign a new value directly to exports, such as exports = add. That does not replace module.exports.

6. CommonJS with Built-in and Local Modules

CommonJS can load different kinds of modules:

Module Type Example Purpose
Built-in require('node:fs') Work with files.
Built-in require('node:path') Work with paths.
Local require('./math') Load your own file.
Installed package require('express') Load an installed package that supports CommonJS.

7. How to Run a CommonJS Program

  1. Install Node.js on your computer.
  2. Create a folder for your project.
  3. Create math.js and app.js.
  4. Write the export code in math.js.
  5. Load the module using require() in app.js.
  6. Open the terminal in your project folder.
  7. Run the command below.
node app.js
Remember: In a typical Node.js project configured for CommonJS, use require() to load modules and module.exports to export values. A file using the .cjs extension is explicitly treated as CommonJS. A .js file's module system also depends on the project's configuration.

8. Practical Assignment

Practice Task
Create a simple student module using CommonJS.
  1. Create a file named student.js.
  2. Create a function named getStudentName() that returns "Amit".
  3. Export the function using module.exports.
  4. Create another file named app.js.
  5. Load the function using require('./student').
  6. Print the returned student name using console.log().

Expected output:

Amit

🧠 Quiz – CommonJS Modules

Select the correct answer for each question.

1. Which function is commonly used to load a CommonJS module?



2. Which property is used to export a function from a CommonJS file?



3. Which path loads a local file named math.js?