Modules in Node.js
⏱ Estimated reading time: 3 min
1. What is a Module?
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
2. Why Modules Are Needed
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
3. Types of Modules in Node.js
3.1 Core (Built-in) Modules
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:
3.2 Local Modules
Modules created by the user and stored in separate files.
Example:
3.3 Third-Party Modules
Modules created by the community and installed via npm.
Example:
4. CommonJS Module System
Node.js uses the CommonJS module system by default.
Key Components
| Component | Description |
|---|---|
require() | Imports a module |
module.exports | Exports functionality |
exports | Shortcut reference |
4.1 Exporting Modules
Single Export
Multiple Exports
⚠ exports is a reference to module.exports
4.2 Importing Modules
5. Module Wrapper Function (Internal Working)
Node.js wraps every module inside a function:
This provides:
-
Private scope
-
Access to module metadata
6. Module Resolution Process
When require() is used, Node.js follows this order:
-
Core modules (
fs,http) -
File or directory (
./module) -
node_modulesfolder -
Looks for:
-
file.js -
file.json -
file.node -
index.js
-
7. Module Caching
-
Modules are cached after first execution
-
Subsequent
require()calls return the cached version -
Code executes only once
✔ Improves performance
⚠ Shared state across imports
8. ES Modules (ESM)
Node.js also supports ES Modules.
Enable ES Modules
-
Use
.mjsextension
OR -
Set
"type": "module"inpackage.json
Exporting (ESM)
Importing (ESM)
9. CommonJS vs ES Modules
| Feature | CommonJS | ES Modules |
|---|---|---|
| Import | require() | import |
| Export | module.exports | export |
| Loading | Synchronous | Asynchronous |
| Usage | Default in Node.js | Modern standard |
10. Best Practices
✔ Keep one module per file
✔ Export only what is required
✔ Use meaningful names
✔ Avoid circular dependencies
✔ Prefer ES Modules for new projects
11. Advantages of Modules
-
Encapsulation
-
Reusability
-
Maintainability
-
Scalability
12. Summary
-
Every Node.js file is a module
-
Supports Core, Local, and Third-Party modules
-
Uses CommonJS and ES Modules
-
Modules are cached for performance
Register Now
Share this Post
← Back to Tutorials