> ## Documentation Index
> Fetch the complete documentation index at: https://bun.ll1025.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 监听目录变化

Bun 实现了 `node:fs` 模块，包括用于监听文件系统变化的 `fs.watch` 函数。

以下代码监听当前目录中文件的变化。默认情况下监听是*浅层的*：不会检测子目录中的文件变化。

```ts theme={null}
import { watch } from "fs";

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

***

要监听子目录中的变化，请向 `fs.watch` 传递 `recursive: true` 选项。

```ts theme={null}
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 theme={null}
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 theme={null}
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 > 二进制数据 > 类型数组](/runtime/binary-data#typedarray) 了解有关在 Bun 中使用 `Uint8Array` 和其他二进制数据格式的更多信息。
