process.getBuiltinModule(id)


process.getBuiltinModule(id) 提供了一种在全局可用函数中加载内置模块的方法。需要支持其他环境的 ES 模块可以使用它来有条件地加载在 Node.js 中运行时内置的 Node.js,而不必处理 import 在非 Node.js 环境中可能抛出的解析错误,也不必使用动态 import() 将模块转换为异步模块,或将同步 API 转换为异步 API。

¥process.getBuiltinModule(id) provides a way to load built-in modules in a globally available function. ES Modules that need to support other environments can use it to conditionally load a Node.js built-in when it is run in Node.js, without having to deal with the resolution error that can be thrown by import in a non-Node.js environment or having to use dynamic import() which either turns the module into an asynchronous module, or turns a synchronous API into an asynchronous one.

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: 前缀的内置模块。即使用户修改 require.cache 以使 require(id) 返回其他内容,process.getBuiltinModule(id) 返回的引用也始终指向与 id 对应的内置模块。

¥process.getBuiltinModule(id) accepts built-in module IDs that are recognized by module.isBuiltin(id). Some built-in modules must be loaded with the node: prefix, see built-in modules with mandatory node: prefix. The references returned by process.getBuiltinModule(id) always point to the built-in module corresponding to id even if users modify require.cache so that require(id) returns something else.