Node.js Modules System

In Node.js, a module is simply a file that contains JavaScript code. Instead of putting all code into one large file, Node.js encourages breaking code into separate files — each handling one specific task. These files are called modules. The module system makes code organized, reusable, and easier to maintain.

Think of modules like chapters in a book. Each chapter covers its own topic, but together they form a complete story. Similarly, each module handles its own feature, and together they build a complete application.

Types of Modules in Node.js

Node.js has three categories of modules:

  • Built-in (Core) Modules: These come pre-installed with Node.js. Examples include fs (file system), path, os, and http.
  • Third-Party Modules: These are created by other developers and installed via npm. Examples include express, mongoose, and lodash.
  • Custom (Local) Modules: These are files created within the project itself. One file can import and use code from another file in the same project.

The CommonJS Module System

Node.js traditionally uses the CommonJS module system, which provides two key tools:

  • module.exports — used to export code from a file so it can be used elsewhere.
  • require() — used to import code from another file or module.

Creating and Using a Custom Module

Step 1 – Create a Module File

Create a file named greet.js:

// greet.js

function sayHello(name) {
  return "Hello, " + name + "!";
}

function sayGoodbye(name) {
  return "Goodbye, " + name + "!";
}

module.exports = { sayHello, sayGoodbye };

Here, two functions are defined and then exported using module.exports. This makes them available for use in other files.

Step 2 – Import the Module in Another File

Create another file named app.js in the same folder:

// app.js

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

console.log(greet.sayHello("Alice"));
console.log(greet.sayGoodbye("Bob"));

Output:

Hello, Alice!
Goodbye, Bob!

The ./ before greet indicates that the file is in the same directory. The .js extension can be omitted — Node.js adds it automatically.

Exporting a Single Value

If only one function or value needs to be exported, it can be assigned directly:

// math.js

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

module.exports = add;
// app.js

const add = require('./math');

console.log(add(3, 7)); // Output: 10

Exporting Multiple Values Using Object Shorthand

// calculator.js

const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
const multiply = (a, b) => a * b;

module.exports = { add, subtract, multiply };
// app.js

const calc = require('./calculator');

console.log(calc.add(10, 5));       // 15
console.log(calc.subtract(10, 5));  // 5
console.log(calc.multiply(10, 5));  // 50

Using Built-in Core Modules

Core modules are loaded using require() without any file path — just the module name:

// Using the built-in 'os' module

const os = require('os');

console.log("Platform:", os.platform());
console.log("CPU Architecture:", os.arch());
console.log("Free Memory:", os.freemem());

No installation is needed for built-in modules. They are always available in any Node.js environment.

The module Object

Every Node.js file automatically has access to a module object. This object contains useful information about the file itself:

// info.js

console.log(module);

When this file is run, the output shows properties like:

  • id — the identifier of the module (usually the file path).
  • filename — the absolute path to the current file.
  • loaded — whether the module has finished loading.
  • exports — the object that will be exposed to other files.
  • parent — the module that required this one.
  • children — modules that this module has required.

ES Modules (ESM) – The Modern Alternative

Node.js also supports the modern ES Module syntax (used in modern browsers and frontend frameworks). Instead of require() and module.exports, ES Modules use import and export.

To use ES Modules, the file must either have a .mjs extension, or the package.json file must contain "type": "module".

// greet.mjs

export function sayHello(name) {
  return "Hello, " + name + "!";
}
// app.mjs

import { sayHello } from './greet.mjs';

console.log(sayHello("Charlie")); // Hello, Charlie!

For beginners, the CommonJS system (require / module.exports) is still the most commonly taught and used approach. ES Modules become more relevant as projects grow or when working with modern frameworks.

Module Caching

Node.js caches modules after the first time they are loaded. This means if the same module is required multiple times in a project, Node.js does not re-run the module code each time — it simply returns the cached version. This improves performance.

// counter.js
let count = 0;
count++;
module.exports = count;
// app.js
const a = require('./counter');
const b = require('./counter');

console.log(a); // 1
console.log(b); // 1 (same cached result, not 2)

Key Points

  • A module is a separate JavaScript file that can share its code with other files.
  • Node.js uses three types of modules: built-in, third-party (npm), and custom (local).
  • Use module.exports to export code and require() to import it.
  • Built-in modules are loaded without a file path — just the module name.
  • Custom modules require a relative path starting with ./.
  • Node.js caches modules after the first load for better performance.
  • ES Modules (import/export) are the modern alternative to CommonJS.

Leave a Comment

Your email address will not be published. Required fields are marked *