process: add process.getBuiltinModule(id)
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');
}
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)
accepts built-in module IDs that are recognized
by module.isBuiltin(id)
.
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.