How to Export Function in Node.js: Simple Guide
In Node.js, you export a function by assigning it to
module.exports or adding it as a property to exports. This makes the function available to other files when you use require().Syntax
To export a function in Node.js, you use either module.exports or exports. module.exports replaces the entire export object, while exports adds properties to the existing export object.
module.exports = functionName;exports a single function.exports.functionName = functionName;exports a named function as a property.
javascript
module.exports = functionName; // or exports.functionName = functionName;
Example
This example shows how to export a function named greet and use it in another file.
javascript
// greet.js function greet(name) { return `Hello, ${name}!`; } module.exports = greet; // app.js const greet = require('./greet'); console.log(greet('Alice'));
Output
Hello, Alice!
Common Pitfalls
A common mistake is mixing exports and module.exports. Assigning a new value to exports alone does not change the exported module. Always use module.exports to export a single function or object.
javascript
// Wrong way: exports = function() { console.log('This will NOT be exported'); }; // Right way: module.exports = function() { console.log('This will be exported'); };
Quick Reference
| Method | Usage | Notes |
|---|---|---|
| module.exports = functionName; | Exports a single function or object | Replaces entire export object |
| exports.functionName = functionName; | Exports multiple named functions | Adds properties to exports object |
| exports = functionName; | Does NOT export function | Overrides local exports variable only |
Key Takeaways
Use module.exports to export a single function or object in Node.js.
Use exports to add multiple named exports as properties.
Never assign directly to exports alone; it won't change the exported module.
Require the exported function in another file using require('./filename').
Remember module.exports replaces the export object, exports adds to it.