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 文件