Skip to content

process: add process.getBuiltinModule(id)#52762

Closed
joyeecheung wants to merge 7 commits intonodejs:mainfrom
joyeecheung:process-builtin
Closed

process: add process.getBuiltinModule(id)#52762
joyeecheung wants to merge 7 commits intonodejs:mainfrom
joyeecheung:process-builtin

Conversation

@joyeecheung
Copy link
Copy Markdown
Member

@joyeecheung joyeecheung commented Apr 30, 2024

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.

Fixes: #52599

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

commit-queue-rebase Add this label to allow the Commit Queue to land a PR in several commits. lib / src Issues and PRs related to general changes in the lib or src directory. needs-ci PRs that need a full CI run. notable-change PRs with changes that should be highlighted in changelogs. semver-minor PRs that contain new features and should be released in the next minor version.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Provide some mechanism to conditionally and synchronously import modules (or just builtins) from ESM