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
Release: 2024-11-18 01:22:02
Original
562 people have browsed it

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) {...}
Copy after login

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() {...}
Copy after login

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");
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template