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

監視目錄變化

Bun 實現了 node:fs 模組,包括用於監聽檔案系統變化的 fs.watch 函式。

以下程式碼會監聽當前目錄中的檔案變化。預設情況下,監聽是_淺層_的:不會檢測子目錄中的檔案變化。

TypeScript
import { watch } from "fs";

const watcher = watch(import.meta.dir, (event, filename) => {
  console.log(`檢測到 ${filename} 的 ${event} 事件`);
});

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

TypeScript
import { watch } from "fs";

const watcher = watch(import.meta.dir, { recursive: true }, (event, relativePath) => {
  console.log(`檢測到 ${relativePath} 的 ${event} 事件`);
});

使用 node:fs/promises 模組時,可以使用 for await...of 代替回撥來監聽變化。

TypeScript
import { watch } from "fs/promises";

const watcher = watch(import.meta.dir);
for await (const event of watcher) {
  console.log(`檢測到 ${event.filename} 的 ${event.eventType} 事件`);
}

要停止監聽變化,呼叫 watcher.close()。通常在行程收到 SIGINT 訊號時執行此操作,比如使用者按下 Ctrl-C 時候。

TypeScript
import { watch } from "fs";

const watcher = watch(import.meta.dir, (event, filename) => {
  console.log(`檢測到 ${filename} 的 ${event} 事件`);
});

process.on("SIGINT", () => {
  // 在按下 Ctrl-C 時關閉監聽器
  console.log("正在關閉監聽器...");
  watcher.close();

  process.exit(0);
});

請參閱 Node.js 文件 中關於 fs.watch 的說明。