module.exports vs exports
1. Definition
In Node.js, both module.exports and exports are used to export data from a module so it can be used in other files. However, they work slightly differently under the hood.
2. module.exports
- Main object that is returned when require() is called
- Can export a function, object, or value
- Used when exporting a single value
3. exports
- Shorthand reference to module.exports
- Used to add multiple properties
- Cannot directly assign a new value
4. Key Differences
- Usage: module.exports → single export | exports → multiple exports
- Assignment: module.exports can be reassigned | exports cannot
- Reference: exports is a reference to module.exports
5. Example
👉 Using module.exports
// math.js
module.exports = function add(a, b) {
return a + b;
};
// app.js
const add = require("./math");
console.log(add(2, 3));👉 Using exports
// math.js
exports.add = (a, b) => a + b;
exports.sub = (a, b) => a - b;
// app.js
const math = require("./math");
console.log(math.add(2, 3));6. Important Note
If you assign a new value to exports, it will break the reference with module.exports and will not work as expected.
// ❌ Wrong
exports = function() {};
// ✅ Correct
module.exports = function() {};7. Advantages
- Helps in modular code structure
- Supports code reuse
- Makes large applications manageable