A module in Node.js is a self-contained block of code that encapsulates related functionality and exposes it for reuse.
Each file in Node.js is treated as a separate module.
✔ Improves code organization
✔ Enables reusability
✔ Prevents global scope pollution
Without modules:
Code becomes hard to manage
Variables pollute global scope
Maintenance becomes difficult
With modules:
Clear separation of concerns
Better scalability
Easy testing and debugging
These are included with Node.js installation.
Examples:
fs – File system operations
http – Create web servers
path – File path handling
os – System information
events – Event handling
Usage:
Modules created by the user and stored in separate files.
Example:
Modules created by the community and installed via npm.
Example:
Node.js uses the CommonJS module system by default.
| Component | Description |
|---|---|
require() | Imports a module |
module.exports | Exports functionality |
exports | Shortcut reference |
⚠ exports is a reference to module.exports
Node.js wraps every module inside a function:
This provides:
Private scope
Access to module metadata
When require() is used, Node.js follows this order:
Core modules (fs, http)
File or directory (./module)
node_modules folder
Looks for:
file.js
file.json
file.node
index.js
Modules are cached after first execution
Subsequent require() calls return the cached version
Code executes only once
✔ Improves performance
⚠ Shared state across imports
Node.js also supports ES Modules.
Use .mjs extension
OR
Set "type": "module" in package.json
| Feature | CommonJS | ES Modules |
|---|---|---|
| Import | require() | import |
| Export | module.exports | export |
| Loading | Synchronous | Asynchronous |
| Usage | Default in Node.js | Modern standard |
✔ Keep one module per file
✔ Export only what is required
✔ Use meaningful names
✔ Avoid circular dependencies
✔ Prefer ES Modules for new projects
Encapsulation
Reusability
Maintainability
Scalability
Every Node.js file is a module
Supports Core, Local, and Third-Party modules
Uses CommonJS and ES Modules
Modules are cached for performance
Take quizzes related to this topic and see where you stand!
Start Quiz Now