Skip to main content
Bun 实现了 node:fs 模块,包括用于监听文件系统变化的 fs.watch 函数。 以下代码块监听当前目录中文件的变化。默认情况下,此操作是浅层的,意味着对子目录中文件的变化将不会被检测到。
import { watch } from "fs";

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

要监听子目录中的变化,请向 fs.watch 传递 recursive: true 选项。
import { watch } from "fs";

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

使用 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(`检测到 ${event.filename}${event.eventType} 事件`);
}

要停止监听变化,调用 watcher.close()。通常在进程收到 SIGINT 信号时执行此操作,比如用户按下 Ctrl-C 时候。
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);
});

有关在 Bun 中处理 Uint8Array 和其他二进制数据格式的更多信息,请参阅 API > 二进制数据 > 类型化数组