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 和其他二進位資料格式的更多資訊。