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 دقیقه مطالعه • بروزرسانی ۸ دی ۱۴۰۴

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.


نوشته و پژوهش شده توسط دکتر شاهین صیامی