Bun 實現了 node:fs 模塊,包括用於監聽文件系統更改的 fs.watch 函數。
此代碼塊監聽當前目錄中文件的更改。默認情況下,此操作是_淺層的_,這意味著不會檢測到子目錄中文件的更改。
ts
import { watch } from "fs";
const watcher = watch(import.meta.dir, (event, filename) => {
console.log(`在 ${filename} 中檢測到 ${event}`);
});要監聽子目錄中的更改,請將 recursive: true 選項傳遞給 fs.watch。
ts
import { watch } from "fs";
const watcher = watch(import.meta.dir, { recursive: true }, (event, relativePath) => {
console.log(`在 ${relativePath} 中檢測到 ${event}`);
});使用 node:fs/promises 模塊,你可以使用 for await...of 而不是回調來監聽更改。
ts
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 時。
ts
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);
});請參閱 API > 二進制數據 > 類型化數組,了解在 Bun 中使用 Uint8Array 和其他二進制數據格式的更多信息。