CommonJS Modules in Node.js

CommonJS modules are the original way of packaging JavaScript code in Node.js. . Each file is treated as a separate module, and modules can be imported using require(). Exports are defined using exports or module.exports. This system allows developers to organize code, manage dependencies, and reuse functionality across applications.

require() / exports / module.exportsbuilt-in modulescaching / require.cache__dirname / __filename

~2 min read · Updated Dec 29, 2025

1. Introduction


In Node.js, every file is a module. For example:


// foo.js
const circle = require('./circle.js');
console.log(`Area: ${circle.area(4)}`);

The module circle.js can export functions using exports or module.exports.


2. Exports and module.exports


  • exports: A shortcut for adding properties to the module’s output.
  • module.exports: Allows replacing the entire module output with an object or class.

3. Enabling CommonJS


  • Files with a .cjs extension.
  • .js files when "type": "commonjs" is specified in package.json.
  • .js files or files without an extension when no type field is present.

4. Accessing the Main Module


require.main can be used to check if a file is executed directly or imported as a module.


5. Dependency Management


Node.js resolves dependencies from node_modules. Symbolic links and directory structures allow managing multiple versions of dependencies.


6. Loading ECMAScript Modules with require()


Experimental support exists for loading ES modules with require(), but limitations apply (e.g., no top-level await).


7. Caching


  • Modules are cached in require.cache after the first load.
  • This prevents re-execution of module code on subsequent imports.

8. Built-in Modules


Node.js includes built-in modules like http, fs, and crypto. Some require the node: prefix.


9. Cyclic Dependencies


When circular dependencies occur, Node.js returns a partially executed module to avoid infinite loops.


10. Files and Folders as Modules


  • Files with .js, .json, or .node extensions can be loaded.
  • Folders can act as modules if they contain a package.json with a main field or an index.js file.

11. Module Wrapper


Node.js wraps each module in a function to provide local scope and special variables like __dirname and __filename.


12. Example


// square.js
module.exports = class Square {
  constructor(width) { this.width = width; }
  area() { return this.width ** 2; }
};

// bar.js
const Square = require('./square.js');
const mySquare = new Square(2);
console.log(mySquare.area()); // 4

Conclusion


The CommonJS module system in Node.js is the foundation for organizing code. Using require(), exports, and module.exports, developers can build reusable modules, manage dependencies, and structure applications effectively.


Written & researched by Dr. Shahin Siami

Related Articles

Comprehensive Guide to the Node.js VM Module (node:vm)

The node:vm module allows you to compile and execute JavaScript code inside isolated V8 contexts — essentially creating lightweight sandboxes within your Node.js application. These contexts have their own global scope and can run code independently from the main environment. However, vm is NOT a security sandbox. It is powerful for dynamic code execution, template engines, REPLs, plugin systems, and controlled module execution, but it must never be used to run untrusted code.

Continue

Comprehensive Guide to the V8 Module in Node.js (node:v8)

The node:v8 module exposes low-level APIs that interact directly with the V8 JavaScript engine embedded in Node.js. . These APIs provide access to heap statistics, heap snapshots, coverage tools, serialization mechanisms, V8 flags, object queries, and promise lifecycle hooks. The module is essential for performance analysis, memory debugging, tooling, and advanced Node.js internals work.

Continue

Comprehensive Guide to Node.js Worker Threads (node:worker_threads)

The node:worker_threads module enables true multithreading in Node.js by running JavaScript in separate threads. While Node.js is traditionally single‑threaded, worker threads allow CPU‑intensive tasks to run in parallel without blocking the event loop. They support shared memory, zero‑copy transfers, worker pools, resource limits, and advanced synchronization APIs. Worker threads are ideal for heavy computation, data processing, and parallel workloads—while async I/O remains best handled by the main thread.

Continue

Comprehensive Guide to the Node.js util Module (node:util)

The node:util module provides a powerful collection of helper functions used throughout Node.js core and extremely useful for application developers. These utilities support debugging, inspection, formatting, type checking, callback/Promise conversions, argument parsing, text encoding, MIME handling, and more. It is one of the most versatile and essential toolkits in the Node.js ecosystem.

Continue

Comprehensive Guide to the URL Module in Node.js

The node:url module provides tools for parsing, constructing, and manipulating URLs. Node.js supports two URL APIs: WHATWG URL API — modern, browser‑compatible, standards‑based. Legacy Node.js URL API — older, Node‑specific, now discouraged. The WHATWG API is the recommended approach for all modern applications. It provides a clean, consistent interface for working with URL components, query parameters, and structured URL patterns.

Continue

راهنمای جامع UDP / Datagram Sockets در Node.js

ماژول node:dgram پیاده‌سازی کامل سوکت‌های UDP را در Node.js فراهم می‌کند. UDP یک پروتکل سبک، بدون اتصال (connectionless) و مناسب برای برنامه‌های بلادرنگ مانند VoIP، بازی‌ها، IoT، سیستم‌های پخش (broadcast) و چندپخشی (multicast) است. این ماژول امکان ساخت سوکت، ارسال و دریافت دیتاگرام، مدیریت TTL، عضویت در گروه‌های multicast، کنترل بافرها، و مدیریت رفتار سطح پایین شبکه را فراهم می‌کند.

Continue