What does module.exports mean?

In Node.js, module.exportsa special object used to export functions, objects, or values ​​in a module so that other files can require()use them through functions. This is part of the CommonJS module system and Node.js supports it natively.

Example

Suppose you have a math.jsfile called which contains an addition function and a subtraction function:

// math.js
function add(a, b) {
    
    
  return a + b;
}

function subtract(a, b) {
    
    
  return a - b;
}

module.exports = {
    
    
  add,
  subtract
};

By using module.exports, you can export addthe and subtractfunctions for use in other Node.js files.

Now, in another file, you can import and use these two functions like this:

// app.js
const math = require('./math');

console.log(math.add(5, 3));  // 输出 8
console.log(math.subtract(5, 3));  // 输出 2

Notice

  • module.exportsAny JavaScript type (function, object, array, string, etc.) can be exported.
  • If you use ES6 syntax, module.exportsand requirecan be replaced with exportand respectively import, but be aware that they have some differences in syntax and functionality.
  • In a module, you can use it multiple times module.exports, but only the last assignment will take effect.

This way, you can organize your code to make it easier to manage and test.

Guess you like

Origin blog.csdn.net/m0_57236802/article/details/133066795