Bun 实现了 node:fs 模块,其中包括用于将内容追加到文件的 fs.appendFile 和 fs.appendFileSync 函数。
你可以使用 fs.appendFile 异步追加数据到文件,如果文件尚不存在则创建文件。内容可以是字符串或 Buffer。
ts
import { appendFile } from "node:fs/promises";
await appendFile("message.txt", "data to append");要使用非 Promise API:
ts
import { appendFile } from "node:fs";
appendFile("message.txt", "data to append", err => {
if (err) throw err;
console.log('"data to append" 已追加到文件!');
});要指定内容的编码:
js
import { appendFile } from "node:fs";
appendFile("message.txt", "data to append", "utf8", callback);要同步追加数据,请使用 fs.appendFileSync:
ts
import { appendFileSync } from "node:fs";
appendFileSync("message.txt", "data to append", "utf8");请参阅 Node.js 文档 获取更多信息。