← 中文资源

简体中文版本

appendFile 追加并创建日志文件

appendFile 在文件缺失时自动创建、存在时只追加:日志逐行落盘不必重写全文件;父目录缺失不会自动创建,要自行捕获 ENOENT 处理。

阅读英文原文

运行结果

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

missing dir: ENOENT
lines: 32
boot: v1.0.0request: /health 200

实现说明

异步边界用 await 处理,失败以 rejected promise 的形式在调用点浮出,不会被静默吞掉。唯一的导入来源是 node:fs/promises(Node.js 内建),暴露出 appendFile、readFile。 演示用的数据放在这几个模块级绑定中:content。

使用要点

  • 无需安装:node:fs/promises 随 Node.js 本体提供。
  • 每一步打印都带着自己的标签:missing dir:、lines:。

常见问题

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

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

核心语句

await appendFile('logs/app.log', 'nope\n').catch(
  (error) => console.log('missing dir:', error.code),
);
await appendFile('app.log', 'request: /health 200\n');
const content = await readFile('app.log', 'utf8');

代码示例

import { appendFile, readFile } from 'node:fs/promises';

// appendFile creates the file when missing and appends each call
await appendFile('app.log', 'boot: v1.0.0\n');
await appendFile('app.log', 'request: /health 200\n');

// Missing parent directories are not created — handle ENOENT yourself
await appendFile('logs/app.log', 'nope\n').catch(
  (error) => console.log('missing dir:', error.code),
);

const content = await readFile('app.log', 'utf8');
console.log('lines:', content.trim().split('\n').length);
console.log(content.trimEnd());