Home >Web Front-end >JS Tutorial >How to Export Modules in Node.js: `module.exports` vs `exports`?

How to Export Modules in Node.js: `module.exports` vs `exports`?

Linda Hamilton
Linda HamiltonOriginal
2024-11-18 01:22:02581browse

How to Export Modules in Node.js:  `module.exports` vs `exports`?

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?

  • module.exports: An object provided by Node.js to the module; assigning a value to it sets the module's exported interface.
  • exports: An alias to module.exports; modifications made to exports are reflected in module.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

  • For exporting multiple values, use module.exports.
  • To export a single value, use either module.exports or exports.
  • Ensure that exports is treated as a reference to module.exports.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn