使用 Linux 原生的 inotify 系统实时监视文件系统变更。watch() 方法返回文件变更事件的 Server-Sent Events (SSE) 流,你可以通过 parseSSEStream() 进行消费。
监视目录的文件系统变更。返回事件的 SSE 流。
const stream = await sandbox.watch(path: string, options?: WatchOptions): Promise<ReadableStream<Uint8Array>>参数:
path- 绝对路径,或相对于/workspace的路径(例如/app/src或src)options(可选):recursive- 是否递归监视子目录(默认:true)include- 要包含的 glob 模式(例如['*.ts', '*.js'])。不能与exclude同时使用。exclude- 要排除的 glob 模式(默认:['.git', 'node_modules', '.DS_Store'])。不能与include同时使用。sessionId- 在其中运行监视的会话(若省略,将使用默认会话,除非将enableDefaultSession设为 false)
返回值:Promise<ReadableStream<Uint8Array>> — FileWatchSSEEvent 对象的 SSE 流
import { parseSSEStream } from "@cloudflare/sandbox";
const stream = await sandbox.watch("/workspace/src", {
recursive: true,
include: ["*.ts", "*.js"],
});
const controller = new AbortController();
for await (const event of parseSSEStream(stream, controller.signal)) {
switch (event.type) {
case "watching":
console.log(`Watch established on ${event.path} (id: ${event.watchId})`);
break;
case "event":
console.log(`${event.eventType}: ${event.path}`);
break;
case "error":
console.error(`Watch error: ${event.error}`);
break;
case "stopped":
console.log(`Watch stopped: ${event.reason}`);
break;
}
}
// Cancel the watch by aborting — cleans up the watcher server-side
controller.abort();import { parseSSEStream } from "@cloudflare/sandbox";
import type { FileWatchSSEEvent } from "@cloudflare/sandbox";
const stream = await sandbox.watch("/workspace/src", {
recursive: true,
include: ["*.ts", "*.js"],
});
const controller = new AbortController();
for await (const event of parseSSEStream<FileWatchSSEEvent>(
stream,
controller.signal,
)) {
switch (event.type) {
case "watching":
console.log(`Watch established on ${event.path} (id: ${event.watchId})`);
break;
case "event":
console.log(`${event.eventType}: ${event.path}`);
break;
case "error":
console.error(`Watch error: ${event.error}`);
break;
case "stopped":
console.log(`Watch stopped: ${event.reason}`);
break;
}
}
// Cancel the watch by aborting — cleans up the watcher server-side
controller.abort();监视流发出的所有 SSE 事件的联合类型。
type FileWatchSSEEvent =
| { type: "watching"; path: string; watchId: string }
| {
type: "event";
eventType: FileWatchEventType;
path: string;
isDirectory: boolean;
timestamp: string;
}
| { type: "error"; error: string }
| { type: "stopped"; reason: string };watching— 监视建立时发出一次。包含watchId以及被监视的path。event— 每次文件系统变更时发出。包含eventType、发生变更的path,以及是否为目录(isDirectory)。error— 监视遇到错误时发出。stopped— 监视停止时发出,并附带reason。
可检测到的文件系统变更类型。
type FileWatchEventType =
| "create"
| "modify"
| "delete"
| "move_from"
| "move_to"
| "attrib";create— 创建了文件或目录modify— 文件内容发生变更delete— 删除了文件或目录move_from— 文件或目录被移走(重命名/移动的源)move_to— 文件或目录被移入此处(重命名/移动的目标)attrib— 文件或目录属性发生变更(权限、时间戳)
监视目录的配置选项。
interface WatchOptions {
/** Watch subdirectories recursively (default: true) */
recursive?: boolean;
/** Glob patterns to include. Cannot be used together with `exclude`. */
include?: string[];
/** Glob patterns to exclude. Cannot be used together with `include`. Default: ['.git', 'node_modules', '.DS_Store'] */
exclude?: string[];
/** Session to run the watch in. If omitted, the sandbox's implicit execution mode is used. */
sessionId?: string;
}将 ReadableStream<Uint8Array> 转换为类型化的事件 AsyncGenerator。接受可选的 AbortSignal 以取消流。
function parseSSEStream<T>(
stream: ReadableStream<Uint8Array>,
signal?: AbortSignal,
): AsyncGenerator<T>;参数:
stream— 由watch()返回的 SSE 流signal(可选)— 用于取消流的AbortSignal。中止后,reader 会被取消,清理操作会传播到服务端。
从消费循环外部停止监视的推荐方式是中止该 signal:
const controller = new AbortController();
// Cancel after 60 seconds
setTimeout(() => controller.abort(), 60_000);
for await (const event of parseSSEStream<FileWatchSSEEvent>(
stream,
controller.signal,
)) {
// process events
}include 与 exclude 选项接受一组有限的 glob 标记,以实现可预期的匹配:
| 标记 | 含义 | 示例 |
|---|---|---|
* |
匹配路径段内的任意字符 | *.ts 匹配 index.ts |
** |
跨目录边界匹配 | **/*.test.ts |
? |
匹配单个字符 | ?.js 匹配 a.js |
不支持字符类([abc])、大括号展开({a,b})以及反斜杠转义。包含这些标记的模式会因验证错误被拒绝。
- 监视文件系统变更指南 — 模式、最佳实践与真实示例
- 管理文件指南 — 文件操作