As your application grows, writing all code in a single file becomes difficult to manage. Node.js modules help us split code into multiple files and reuse them easily.
Splitting code into reusable modules in Node.js
1. What is a Module?
A module is a separate file that contains specific functionality. We can export it and use it in another file.
- Clean
- Reusable
- Maintainable
2. Creating Your First Module
Create a file named math.js
function add(a, b) {
return a + b;
}
module.exports = add;
3. Importing the Module
Create another file app.js
const add = require("./math");
console.log(add(5, 3));
Output:
8
4. Exporting Multiple Values
function add(a, b) {
return a + b;
}
function sub(a, b) {
return a - b;
}
module.exports = { add, sub };
Importing:
const math = require("./math");
console.log(math.add(10, 5));
5. exports vs module.exports
- module.exports → Export values
- exports → Shortcut
6. Types of Modules
- Local Modules
- Core Modules (fs, http, path)
- Third-party Modules
7. Real-World Usage
- Database connections
- Authentication logic
- Utility functions
- API services
8. Common Beginner Mistakes
- Missing ./ in path
- Wrong file name
- Not exporting
Without modules, large applications become difficult to manage.
Conclusion
Now you are writing modular and professional Node.js code.
Your Hero to Zero Node.js journey is becoming production-ready ⚡🚀
Tags
NodeJS