What are Modules in Node.js?
1. Definition
Modules in Node.js are reusable blocks of code that can be imported and used in different files. They help organize code into smaller, manageable parts.
2. Types of Modules
- Core Modules: Built into Node.js (e.g., http, fs)
- Local Modules: Custom modules created by developers
- Third-party Modules: Installed using npm (e.g., express)
3. Why We Use Modules
- Organize code into smaller parts
- Improve code reusability
- Make applications easier to maintain
- Avoid code duplication
4. How Modules Work
- Export functionality using module.exports
- Import using require()
- Each file acts as a separate module
5. Example
👉 math.js (module file)
function add(a, b) {
return a + b;
}
module.exports = add;👉 app.js (main file)
const add = require("./math");
console.log(add(2, 3));6. Advantages
- Better code organization
- Reusable components
- Easy maintenance
- Scalable applications
7. Disadvantages
- Too many modules can increase complexity
- Requires proper structure and management