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 文檔 獲取更多信息。