Skip to content

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 和其他二进制数据格式的更多信息。

Bun学习网由www.bunjs.com.cn整理维护