实现说明
逻辑集中在函数 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);