執行環境套件管理器打包器測試執行器程式碼檢查格式化指南參考部落格意見回饋

追加內容到檔案

Bun 實現了 node:fs 模組,其中包括用於向檔案追加內容的 fs.appendFile 和 fs.appendFileSync 函式。


fs.appendFile 非同步地向檔案追加資料,如果檔案尚不存在,則建立該檔案。內容可以是字串或 Buffer。

TypeScript
import { appendFile } from "node:fs/promises";

await appendFile("message.txt", "data to append");

若要使用非 Promise API:

TypeScript
import { appendFile } from "node:fs";

appendFile("message.txt", "data to append", err => {
  if (err) throw err;
  console.log('已將 "data to append" 追加到檔案!');
});

若要指定內容的編碼:

JavaScript
import { appendFile } from "node:fs";

appendFile("message.txt", "data to append", "utf8", callback);

要同步追加資料,請使用 fs.appendFileSync:

TypeScript
import { appendFileSync } from "node:fs";

appendFileSync("message.txt", "data to append", "utf8");

請參閱 Node.js 文件 以瞭解 fs.appendFile。