Node.js v18.12.1 documentation


Table of contents

Modules: CommonJS modules#

Stability: 2 - Stable

CommonJS modules are the original way to package JavaScript code for Node.js. CommonJS模块是为Node.js打包JavaScript代码的原始方法。Node.js also supports the ECMAScript modules standard used by browsers and other JavaScript runtimes.Node.js还支持浏览器和其他JavaScript运行时使用的ECMAScript模块标准。

In Node.js, each file is treated as a separate module. For example, consider a file named foo.js:在Node.js中,每个文件都被视为一个单独的模块。例如,考虑一个名为foo.js的文件:

const circle = require('./circle.js');
console.log(`The area of a circle of radius 4 is ${circle.area(4)}`);

On the first line, foo.js loads the module circle.js that is in the same directory as foo.js.在第一行,foo.js加载与foo.js位于同一目录中的模块circle.js

Here are the contents of circle.js:以下是circle.js的内容:

const { PI } = Math;

exports.area = (r) => PI * r ** 2;

exports.circumference = (r) => 2 * PI * r;

The module circle.js has exported the functions area() and circumference(). circle.js模块已导出函数area()circference()Functions and objects are added to the root of a module by specifying additional properties on the special exports object.通过在特殊导出对象上指定其他属性,可以将函数和对象添加到模块的根。

Variables local to the module will be private, because the module is wrapped in a function by Node.js (see module wrapper). 模块的本地变量将是私有的,因为模块由Node.js封装在函数中(参见模块包装器)。In this example, the variable PI is private to circle.js.在本例中,变量PIcircle.js的私有变量。

The module.exports property can be assigned a new value (such as a function or object).可以为module.exports属性分配一个新值(例如函数或对象)。

Below, bar.js makes use of the square module, which exports a Square class:下面,bar.js使用了square模块,该模块导出一个Square类:

const Square = require('./square.js');
const mySquare = new Square(2);
console.log(`The area of mySquare is ${mySquare.area()}`);

The square module is defined in square.js:square模块定义为square.js

// Assigning to exports will not modify module, must use module.exports
module.exports = class Square {
constructor(width) {
this.width = width;
}

area() {
return this.width ** 2;
}
};

The CommonJS module system is implemented in the module core module.CommonJS模块系统在module核心模块中实现。