0
0
NodejsComparisonBeginner · 3 min read

Module.exports vs exports in Node.js: Key Differences and Usage

In Node.js, 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.

Aspectmodule.exportsexports
TypeObject that Node.js returns as the moduleShortcut reference to module.exports
Default ValueEmpty object {}Points to module.exports initially
Reassignment EffectReplaces the exported moduleReassignment breaks the link and does not export
Adding PropertiesAdds properties to the export objectAdds properties to module.exports via reference
Common UsageUsed to export a single value or objectUsed to add multiple properties or methods
RiskNone when used properlyCan 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

javascript
// Using module.exports to export a function
module.exports = function greet() {
  return 'Hello from module.exports!';
};
↔️

exports Equivalent

javascript
// 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.
Reassigning module.exports replaces the export; reassigning exports does not.
Use module.exports for single exports and exports for multiple properties.
Avoid bugs by not assigning a new value directly to exports.