Publish an object API
A module should expose several named functions or values through one CommonJS import.
Node.js · Pipe
module.exports defines the value a CommonJS module exposes to callers. Assign an object, function, or other value to it, and require() receives that value.
module.exports is the CommonJS module value exposed to consumers. Assign an object, function, or other value to it; a later require() receives that assigned value.
module.exports = value;The value assigned to module.exports; this is the value returned to a consumer by require().
module.exports to choose the public value that CommonJS consumers receive from require().exports provides a shorter reference to the current module.exports value.exports binding is established before the module code runs.exports initially refers to the same value, but reassigning exports alone does not replace module.exports.// math.js
module.exports = {
add(a, b) {
return a + b;
}
};
// app.js
const math = require('./math.js');
console.log(math.add(2, 3));Assigning an object makes its properties available to code that loads the CommonJS module with require().
A module should expose several named functions or values through one CommonJS import.
A module should be called directly after it is loaded.
A package needs one deliberate public surface while keeping implementation details module-local.
module.exports used for?module.exports defines the value a CommonJS module makes available through require(). It can be assigned an object, function, or another value.
Follow-up: What does exports mean? It is initially a shorter reference to module.exports; assigning a new value to exports does not update the module's exported value.
A module can export an object by assigning that object to module.exports. The importing code receives the object returned by require().
Follow-up: How would you export a callable module with helper properties? Assign the main function to module.exports, then add properties to that function before consumers require it.
require() receive from a CommonJS module?Node evaluates each file as a separate module, and module.exports is the value exposed from that module. require() returns that exported value to the caller.
Follow-up: Why can module-local variables remain private? The module system evaluates the file in its own module scope, so only values attached to the exported value are exposed.
exportsrequire()modulemodule.require()Modules: CommonJS modules