In Node.js, module.exports
a 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.js
file 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 add
the and subtract
functions 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.exports
Any JavaScript type (function, object, array, string, etc.) can be exported.- If you use ES6 syntax,
module.exports
andrequire
can be replaced withexport
and respectivelyimport
, 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.