Bun

指南讀取檔案

使用 Bun 監看目錄變更

Bun 實作了 node:fs 模組,包含用於監聽檔案系統變更的 fs.watch 函數。

這段程式碼區塊監聽目前目錄中檔案的變更。預設情況下,此操作是淺層的,表示不會偵測到子目錄中檔案的變更。

import { watch } from "fs";

const watcher = watch(import.meta.dir, (event, filename) => {
  console.log(`Detected ${event} in ${filename}`);
});

若要監聽子目錄中的變更,請將 recursive: true 選項傳遞給 fs.watch

import { watch } from "fs";

const watcher = watch(
  import.meta.dir,
  { recursive: true },
  (event, filename) => {
    console.log(`Detected ${event} in ${filename}`);
  },
);

使用 node:fs/promises 模組,您可以使用 for await...of 而非回呼來監聽變更。

import { watch } from "fs/promises";

const watcher = watch(import.meta.dir);
for await (const event of watcher) {
  console.log(`Detected ${event.eventType} in ${event.filename}`);
}

若要停止監聽變更,請呼叫 watcher.close()。常見的做法是在程序接收到 SIGINT 訊號時執行此操作,例如當使用者按下 Ctrl-C 時。

import { watch } from "fs";

const watcher = watch(import.meta.dir, (event, filename) => {
  console.log(`Detected ${event} in ${filename}`);
});

process.on("SIGINT", () => {
  // close watcher when Ctrl-C is pressed
  console.log("Closing watcher...");
  watcher.close();

  process.exit(0);
});

請參閱API > 二進制資料 > 類型化陣列,以取得更多關於在 Bun 中使用 Uint8Array 和其他二進制資料格式的資訊。