Module Exportation in Node.js: module.exports vs exports
Node.js modules facilitate code reuse and organization by enabling the sharing of functions and data across different modules. Central to module exportation are two key terms: module.exports and exports.
What are module.exports and exports?
Why use both?
In the example provided, both module.exports and exports are employed to maintain backward compatibility.
By default, module.exports points to an empty object. The code:
exports = nano = function database_module(cfg) {...}
adds a function nano to exports and assigns the reference to module.exports. This allows developers to export a function by assigning it to exports, as in:
exports.someFunction = function() {...}
However, this practice can lead to issues when multiple functions are exported in a single line:
exports.a = function() { console.log("a"); } exports.b = function() { console.log("b"); }
In this situation, the exports object is reassigned, causing a clean break between module.exports and exports. To avoid this, the reference to module.exports is explicitly assigned.
Best Practices
The above is the detailed content of How to Export Modules in Node.js: `module.exports` vs `exports`?. For more information, please follow other related articles on the PHP Chinese website!