31
loading...
This website collects cookies to deliver better user experience
module
. This module holds information about that specific file. The module variable is an object, which has a property called exports.require
.package.json
file.module.exports
object. The module system extends the CommonJS
standard. Starting with Node.js v16 the ESM (EcmaScript Modules) are used, see docs.In the early days of Node.js, there was no explicit module system that the language used, so CommonJS was adopted and extended to fill the gap and set forth a standard the community can use. If the NPM registry is the heart of the Node.js ecosystem, then CommonJS and the module system are the backbone.
// math.js
const multiplyByTwo = function(x) {
return x * 2;
};
module.exports = multiplyByTwo;
math.js
, by assigning the function to module.exports
.module.exports
, and then include that value elsewhere by passing the file's path to the require
function. The require function loads a file or package and returns the value assigned to module.exports.// index.js
const multiplyByTwo = require('./math.js');
console.log(multiplyByTwo(10));
// 20
module.exports
:// mathFunctions.js
const add = function(x, y) {
return x + y;
};
const subtract = function(x, y) {
return x - y;
};
const multiplyByTwo = function(x) {
return x * 2;
};
module.exports = {
add,
subtract,
multiplyByTwo,
};
exports
, which is available in each file, but it is an alias of module.exports
.// mathFunctions.js
exports.add = function(x, y) {
return x + y;
};
exports.subtract = function(x, y) {
return x - y;
};
exports.multiplyByTwo = function(x) {
return x * 2;
};
exports
and module.exports
usages, it might result in a loss of the previous used reference.module.exports
is only half of the module system. You need a way to import the code in other parts of the application. You can do that with the require
function.module.exports
from the file. When requiring an npm package , the name of the package is passed to the require
function, and the same thing is happening in the node_modules/
folderimport
and export
keywords when dealing with modules. This is available in the current version of Node.js (v.16). If you are below this Node.js version you can use a transpiler like Babel to convert ESM import and export code into regular CommonJS format through adding a build step to the project.module
object or the exports
object, we can export code from a file to use elsewhere, while keeping some parts of the module encapsulated in their own private scope.