How to Export Module in Node.js: Simple Guide
In Node.js, you export a module by assigning the object, function, or value you want to share to
module.exports. Alternatively, you can add properties to exports as a shortcut to export multiple items.Syntax
Use module.exports to export a single item like a function or object. Use exports to add multiple properties or functions to export. Both are objects representing what your module shares with other files.
module.exports = value;exports one value.exports.name = value;adds named exports.
javascript
module.exports = value; // or exports.name = value;
Example
This example shows how to export a function and an object from a module, then import and use them in another file.
javascript
// file: mathUtils.js function add(a, b) { return a + b; } const constants = { pi: 3.14159 }; module.exports = { add, constants }; // file: app.js const mathUtils = require('./mathUtils'); console.log(mathUtils.add(2, 3)); // 5 console.log(mathUtils.constants.pi); // 3.14159
Output
5
3.14159
Common Pitfalls
A common mistake is mixing module.exports and exports incorrectly. exports is a shortcut to module.exports, but if you assign a new value directly to exports, it breaks the link and nothing gets exported.
Always assign to module.exports when exporting a single item. Use exports.property only to add properties.
javascript
// Wrong way - breaks export exports = function() { console.log('Hello'); }; // Right way module.exports = function() { console.log('Hello'); };
Quick Reference
Remember these tips when exporting modules in Node.js:
- Use
module.exportsto export a single value. - Use
exports.name = valueto export multiple named items. - Do not assign directly to
exportsalone. - Require modules with
require('./moduleName').
Key Takeaways
Use module.exports to export a single function, object, or value from a Node.js module.
Use exports.property to add multiple named exports without overwriting module.exports.
Never assign directly to exports alone, as it breaks the export link.
Import exported modules using require('./moduleName') to access their contents.
Keep exports consistent to avoid unexpected undefined imports.