Intermediate Node.js Interview QuestionsIntermediateConcept
Node.js · Question 38
What is the difference between exports and module.exports in Node.js?
Direct answer
module.exports is the actual export object require() returns; exports is a shorthand reference to it — reassigning exports breaks the link, but adding properties to exports works; set module.exports to a function or class when that is the whole export.
At load time Node sets exports = module.exports — they start as the same object. Interview questions often trap candidates who reassign exports to a new object.
| Pattern | Works? | Why |
|---|---|---|
| exports.foo = 1 | Yes | Mutates shared module.exports object |
| module.exports = { foo: 1 } | Yes | Replaces export wholesale |
| exports = { foo: 1 } | No | Rebinds local exports variable only |
| module.exports = function() {} | Yes | Single function export pattern |
- ESM equivalent — export default / export { named } — no module.exports.
- Barrel files — re-export from index.cjs: module.exports = require('./impl');
exports-pattern.cjs
// Correct: attach properties
exports.parse = (s) => JSON.parse(s);
// Correct: replace entire export
module.exports = function createServer() {
return http.createServer();
};
// Wrong — importers still get old object
// exports = { parse: (s) => JSON.parse(s) };
// require('./exports-pattern.cjs') returns createServer function