Bun

指南寫入檔案

使用 Bun 將內容附加到檔案

Bun 實作了 node:fs 模組,其中包含用於將內容附加到檔案的 fs.appendFilefs.appendFileSync 函式。

你可以使用 fs.appendFile 非同步地將資料附加到檔案,如果檔案尚未存在,則會建立檔案。內容可以是字串或 Buffer

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

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

若要使用非 Promise API

import { appendFile } from "node:fs";

appendFile("message.txt", "data to append", err => {
  if (err) throw err;
  console.log('The "data to append" was appended to file!');
});

若要指定內容的編碼

import { appendFile } from "node:fs";

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

若要同步附加資料,請使用 fs.appendFileSync

import { appendFileSync } from "node:fs";

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

請參閱 Node.js 文件 以取得更多資訊。