← 中文资源

简体中文版本

getBuiltinModule 同步加载内置模块

process.getBuiltinModule('node:fs') 在函数体内同步取内置模块,按 node: 规范名解析,本地文件或 npm 包都无法遮蔽真身。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

total=42
total=7.5
function

实现说明

逻辑集中在函数 writeReceipt里。

使用要点

  • node:fs 是 Node.js 内建模块——随运行时自带,无需安装。

常见问题

它从项目之外导入了什么?

只有 node:fs,而它是 Node.js 内建的——随运行时提供。

签名一览:function writeReceipt(total)

核心语句

return fs.readFileSync('receipt.txt', 'utf8').trim();

代码示例

// 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);