实现说明
异步边界用 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());