Module.exports vs exports in Node.js: Key Differences and Usage
module.exports is the actual object returned by a module, while exports is a shortcut reference to it. Assigning directly to module.exports replaces the exported object, but reassigning exports alone does not change the exported module.Quick Comparison
This table summarizes the main differences between module.exports and exports in Node.js.
| Aspect | module.exports | exports |
|---|---|---|
| Type | Object that Node.js returns as the module | Shortcut reference to module.exports |
| Default Value | Empty object {} | Points to module.exports initially |
| Reassignment Effect | Replaces the exported module | Reassignment breaks the link and does not export |
| Adding Properties | Adds properties to the export object | Adds properties to module.exports via reference |
| Common Usage | Used to export a single value or object | Used to add multiple properties or methods |
| Risk | None when used properly | Can cause bugs if reassigned directly |
Key Differences
module.exports is the actual object that Node.js returns when you require a module. It starts as an empty object, and you can assign any value to it to define what the module exports.
exports is a variable that initially points to the same object as module.exports. It is a convenience to add properties to the export object without replacing it entirely.
The key difference is that if you assign a new value directly to exports, it breaks the connection to module.exports, so the new value is not exported. However, adding properties to exports works because it modifies the original object referenced by module.exports.
Code Comparison
// Using module.exports to export a function module.exports = function greet() { return 'Hello from module.exports!'; };
exports Equivalent
// Using exports to add a function property exports.greet = function() { return 'Hello from exports!'; };
When to Use Which
Choose module.exports when you want to export a single value, function, or object as the module's main export. This replaces the entire export object.
Choose exports when you want to add multiple properties or methods to the export object without replacing it. Avoid reassigning exports directly to prevent breaking the export.
Key Takeaways
module.exports defines the actual exported object from a module.exports is a shortcut to add properties to module.exports but should not be reassigned.module.exports replaces the export; reassigning exports does not.module.exports for single exports and exports for multiple properties.exports.