process.getBuiltinModule(id)
id<string> 请求的内置模块的ID。- 返回:<Object> | <undefined>
process.getBuiltinModule(id) 提供了一种方法,可以在全局可用的函数中加载内置模块。需要支持其他环境的 ES 模块可以使用它,在 Node.js 环境下有条件地加载 Node.js 内置模块,而无需处理在非 Node.js 环境中 import 可能抛出的解析错误,也无需使用动态 import(),后者要么将模块变为异步模块,要么将同步 API 变为异步 API。
if (globalThis.process?.getBuiltinModule) {
// Run in Node.js, use the Node.js fs module.
const fs = globalThis.process.getBuiltinModule('fs');
// If `require()` is needed to load user-modules, use createRequire()
const module = globalThis.process.getBuiltinModule('module');
const require = module.createRequire(import.meta.url);
const foo = require('foo');
} 如果 id 指定了当前 Node.js 进程中可用的内置模块,process.getBuiltinModule(id) 方法将返回相应的内置模块。如果 id 不对应任何内置模块,则返回 undefined。
【If id specifies a built-in module available in the current Node.js process,
process.getBuiltinModule(id) method returns the corresponding built-in
module. If id does not correspond to any built-in module, undefined
is returned.】
process.getBuiltinModule(id) 接受 module.isBuiltin(id) 识别的内置模块 ID。某些内置模块必须使用 node: 前缀加载,详见 具有强制 node: 前缀的内置模块。process.getBuiltinModule(id) 返回的引用总是指向对应 id 的内置模块,即使用户修改了 require.cache,使得 require(id) 返回其他内容。