Sandboxesでのリアルタイムファイル監視
2026年3月3日
Sandboxesがsandbox.watch()を通じてリアルタイムファイルシステム監視をサポートするようになりました。このメソッドはネイティブinotifyに基づくServer-Sent Eventsストリームを返すため、コンテナ内で発生するcreate、modify、delete、moveイベントをWorkerがリアルタイムで受信できます。
sandbox.watch(path, options)
ディレクトリパスとオプションのフィルターを渡します。返されるストリームは標準的なReadableStreamで、ブラウザクライアントに直接プロキシしたり、サーバーサイドで消費したりできます。
JavaScript
const stream = await sandbox.watch("/workspace/src", {
recursive: true,
include: ["*.ts", "*.js"],
});
return new Response(stream, {
headers: { "Content-Type": "text/event-stream" },
});
TypeScript
const stream = await sandbox.watch("/workspace/src", {
recursive: true,
include: ["*.ts", "*.js"],
});
return new Response(stream, {
headers: { "Content-Type": "text/event-stream" },
});
parseSSEStreamを使用したサーバーサイド消費
parseSSEStreamを使用して、クライアントに転送することなくWorker内でイベントを反復処理できます。
JavaScript
import { parseSSEStream } from "@cloudflare/sandbox";
const stream = await sandbox.watch("/workspace/src", {
recursive: true
});
for await (const event of parseSSEStream(stream)) {
console.log(event.type, event.path);
}
TypeScript
import { parseSSEStream } from "@cloudflare/sandbox";
import type { FileWatchSSEEvent } from "@cloudflare/sandbox";
const stream = await sandbox.watch("/workspace/src", {
recursive: true
});
for await (const event of parseSSEStream<FileWatchSSEEvent>(stream)) {
console.log(event.type, event.path);
}
各イベントにはtypeフィールド(create、modify、delete、またはmove)と影響を受けたpathが含まれます。moveイベントには元のパスを含むfromフィールドも含まれます。
オプション
| オプション | 型 | 説明 |
|---|
| recursive | boolean | サブディレクトリを監視します。デフォルトはfalseです。 |
| include | string[] | イベントをフィルタリングするためのGlobパターン。すべてのイベントを受信するには省略します。 |
アップグレード
最新バージョンに更新するには:
npm i @cloudflare/sandbox@latest
完全なAPI詳細については、Sandboxファイル監視リファレンスを参照してください。