getBuiltinModule Loads Builtins Synchronously

Load node builtins synchronously inside a function with process.getBuiltinModule, so request paths skip top-level await and import hoisting.

JavascriptSecurity Boundaries

Code

javascriptsnippet
16 lines
// process.getBuiltinModule('node:fs') loads a builtin synchronously
// from inside a function body — no top-level await, and the module
// only loads when the code path actually runs
function writeReceipt(total) {
  const fs = process.getBuiltinModule('node:fs');
  fs.writeFileSync('receipt.txt', `total=${total}\n`, 'utf8');
  return fs.readFileSync('receipt.txt', 'utf8').trim();
}

console.log(writeReceipt(42));
console.log(writeReceipt(7.5));

// Resolution goes through the canonical node: specifier, so a local
// file or an npm package named "fs" cannot shadow the real builtin
const url = process.getBuiltinModule('node:url');
console.log(typeof url.fileURLToPath);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

total=42
total=7.5
function

Loading a builtin inside a function body

writeReceipt(total) calls process.getBuiltinModule('node:fs') at the moment the function runs — no top-level await, and the module only loads when this code path actually executes. It writes `total=${total}\n` to receipt.txt, reads the file back, and returns the trimmed content, so the console shows the round-tripped text: total=42 then total=7.5.

Canonical resolution cannot be shadowed

The third output line is function — the value of typeof url.fileURLToPath after process.getBuiltinModule('node:url'). Because resolution goes through the canonical node: specifier, a local file or npm package named fs or url cannot shadow the real builtin the way a bare-specifier import could.

The line that fetches on demand

const fs = process.getBuiltinModule('node:fs');
fs.writeFileSync('receipt.txt', `total=${total}\n`, 'utf8');

The lookup itself is synchronous and cached by the runtime, so repeated calls cost no import machinery — the win is that a rarely used builtin never loads at all unless its function is actually invoked.

Interactive Tools for This Topic

FAQ

What does this import from outside the project?
Only `node:fs`, and that is a Node.js built-in — it comes with the runtime.