Reference Reference reference

Node.js fs.readFile 参考

Node.js fs.readFile 是 Node.js 核心能力的一部分。ESM 中推荐使用 node: 前缀导入;CommonJS 中可使用 require("node:fs")。

语法

text
fs.readFile(path[, options])

最小示例

js
import { readFile } from 'node:fs/promises';
const pkg = JSON.parse(await readFile('package.json', 'utf8'));
console.log(pkg.scripts);

常见错误

  • 混用 ESM 与 CommonJS,导致导入方式不一致。
  • 忽略异步错误,未使用 try/catch 或错误事件处理。
  • 把示例路径写死到特定系统,导致 Windows 和 Linux 表现不同。

相关内容