内置模块
¥Built-in modules
内置模块 提供其公共 API 的命名导出。还提供了默认导出,其是 CommonJS 导出的值。默认导出可用于修改命名导出等。内置模块的命名导出只能通过调用 module.syncBuiltinESMExports() 来更新。
¥Built-in modules provide named exports of their public API. A
default export is also provided which is the value of the CommonJS exports.
The default export can be used for, among other things, modifying the named
exports. Named exports of built-in modules are updated only by calling
module.syncBuiltinESMExports().
import EventEmitter from 'node:events';
const e = new EventEmitter(); import { readFile } from 'node:fs';
readFile('./foo.txt', (err, source) => {
if (err) {
console.error(err);
} else {
console.log(source);
}
}); import fs, { readFileSync } from 'node:fs';
import { syncBuiltinESMExports } from 'node:module';
import { Buffer } from 'node:buffer';
fs.readFileSync = () => Buffer.from('Hello, ESM');
syncBuiltinESMExports();
fs.readFileSync === readFileSync; 导入内置模块时,即使未单独访问,所有命名导出(即模块导出对象的属性)也会被填充。与使用
require()或process.getBuiltinModule()加载内置模块相比,此方法可能会导致初始导入速度略慢。使用require()或process.getBuiltinModule()加载时,模块导出的对象会立即被解析,但其某些属性可能仅在首次单独访问时才会初始化。¥When importing built-in modules, all the named exports (i.e. properties of the module exports object) are populated even if they are not individually accessed. This can make initial imports of built-in modules slightly slower compared to loading them with
require()orprocess.getBuiltinModule(), where the module exports object is evaluated immediately, but some of its properties may only be initialized when first accessed individually.