Understanding the Node.js Module System

Understanding how Node.js handles modules is essential for structuring your applications efficiently. Node.js uses the CommonJS module system, which allows developers to split code into reusable components.


Table of Contents

  1. What Are Modules in Node.js?
  2. Types of Modules
  3. Creating and Exporting Your Own Modules
  4. Importing Modules
  5. The require Function
  6. module.exports vs exports
  7. Built-in Modules
  8. Using External Modules
  9. Conclusion

1. What Are Modules in Node.js?

A module in Node.js is simply a JavaScript file. It helps you organize code into smaller, reusable pieces. Instead of writing all the logic in one file, modules let you split it across multiple files.


2. Types of Modules

Node.js supports three types of modules:

  • Core Modules – Built into Node.js (e.g., fs, http, path)
  • Local Modules – Custom modules you write in your project
  • Third-Party Modules – Installed via npm (e.g., express, lodash)

3. Creating and Exporting Your Own Modules

Let’s create a simple math module:

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

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

module.exports = { add, multiply };

4. Importing Modules

To use the above module in another file:

// app.js
const math = require('./math');

console.log(math.add(5, 3)); // Output: 8
console.log(math.multiply(4, 2)); // Output: 8

5. The require Function

Node’s require() is used to import modules. When you pass a string to require(), Node resolves the path and loads the file or package.

Example:

const fs = require('fs');

6. module.exports vs exports

Both can be used to export functionality from a module, but they are not the same.

// This works
module.exports.sayHi = () => console.log("Hi");

// This is fine too
exports.sayHi = () => console.log("Hi");

// This breaks the reference
exports = { sayHi: () => console.log("Hi") };

Use module.exports when exporting a complete object or function.


7. Built-in Modules

Node.js includes several core modules that require no installation:

const path = require('path');
console.log(path.basename('/foo/bar/baz.txt')); // Output: baz.txt

Other popular built-in modules:

  • fs – File system
  • http – HTTP server
  • os – Operating system utilities
  • events – Event emitter class

8. Using External Modules

To use third-party modules:

npm install lodash

Then in your file:

const _ = require('lodash');

console.log(_.capitalize('node.js')); // Output: Node.js

9. Conclusion

The module system is one of Node.js’s most powerful features. Whether you’re using core modules, writing your own, or leveraging third-party libraries, mastering modules is key to building clean and maintainable applications.