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

# Watch a directory for changes

> Watch a sandbox directory for create, write, remove, rename and chmod events with Node.js callbacks, Python async callbacks or Python sync polling.

A watcher reports filesystem events in a directory inside the sandbox: a file or directory is created, written, removed, renamed, or has its permissions changed. The Node.js SDK and the Python async SDK call a callback for each event. The Python sync SDK returns the events when polled. All three return a handle that is stopped with `stop()`.

> [!NOTE]
>
> Install the SDK, or the CLI for `ppio` commands, and set the `PPIO_API_KEY` and `PPIO_DOMAIN` environment variables before running these examples. See [Quickstart](https://docs.ppio.ai/sandbox/quickstart.md) and [Install and authenticate](https://docs.ppio.ai/sandbox/cli/install.md).

## Event object and event types

Each event is a `FilesystemEvent` with two fields.

**name** `string`

Relative path to the filesystem object.

**type** `FilesystemEventType`

The kind of filesystem operation.

The `type` is one of the `FilesystemEventType` values.

**FilesystemEventType.CHMOD** `FilesystemEventType`

Value `chmod`. Object permissions were changed.

**FilesystemEventType.CREATE** `FilesystemEventType`

Value `create`. Object was created.

**FilesystemEventType.REMOVE** `FilesystemEventType`

Value `remove`. Object was removed.

**FilesystemEventType.RENAME** `FilesystemEventType`

Value `rename`. Object was renamed.

**FilesystemEventType.WRITE** `FilesystemEventType`

Value `write`. Object was written to.

## Watch a directory

> [tab] Node.js
>
> `watchDir(path, onEvent, opts?)` starts watching and calls `onEvent` for each event. It returns a `WatchHandle`; call `stop()` to stop watching.
>
> **path** `string`
>
> Directory to watch.
>
> **onEvent** `(event: FilesystemEvent) =\> void`
>
> Called for each event.
>
> **opts** `object`
>
> Optional. Options that control the watch.
>
> **opts**
>
> **recursive** `boolean` (default: false)
>
> Watch subdirectories too.
>
> **timeoutMs** `number` (default: 60000)
>
> Watch timeout in milliseconds; `0` disables it.
>
> **onExit** `(err?: Error) =\> void`
>
> Called when watching stops.
>
> **user** `string`
>
> Run the operation as this user.
>
> ```javascript Node.js theme={null}
> // index.mts
> import { PPIO } from 'ppio-sandbox'
>
> const ppio = new PPIO()
> const sandbox = await ppio.codeInterpreter.create()
>
> const handle = await sandbox.files.watchDir(
>   '/tmp',
>   (event) => {
>     console.log(`[${event.type}] ${event.name}`)
>   },
>   { recursive: true }
> )
>
> // ... trigger some file changes ...
>
> await handle.stop()
> await sandbox.kill()
> ```

> [tab] Python async
>
> The Python async SDK uses a callback model: pass an `on_event` callback to `watch_dir`, which returns an `AsyncWatchHandle`. Stop it with `await handle.stop()`.
>
> ```python Python theme={null}
> import asyncio
> from ppio_sandbox.code_interpreter import AsyncSandbox
>
> async def main():
>     sandbox = await AsyncSandbox.create()
>
>     def on_event(e):
>         print(f'[{e.type.value}] {e.name}')
>
>     handle = await sandbox.files.watch_dir('/tmp', on_event=on_event, recursive=True)
>
>     # ... trigger some file changes ...
>
>     await handle.stop()
>     await sandbox.kill()
>
> asyncio.run(main())
> ```

> [tab] Python sync
>
> The Python sync SDK uses a polling model: `watch_dir(path, recursive=False)` returns a `WatchHandle`, and `get_new_events()` returns the events that occurred since the last call. Stop it with `stop()`.
>
> **path** `str`
>
> Directory to watch.
>
> **user** `str`
>
> Optional. Run the operation as this user.
>
> **request\_timeout** `float`
>
> Optional. Request timeout in seconds.
>
> **recursive** `bool` (default: False)
>
> Watch subdirectories too.
>
> ```python Python theme={null}
> import time
> from ppio_sandbox import PPIO
>
> ppio = PPIO()
> sandbox = ppio.code_interpreter.create()
>
> watcher = sandbox.files.watch_dir('/tmp', recursive=True)
>
> try:
>     for _ in range(10):
>         events = watcher.get_new_events()
>         for e in events:
>             print(f'[{e.type.value}] {e.name}')
>         time.sleep(1)
> except KeyboardInterrupt:
>     pass
> finally:
>     watcher.stop()
>     sandbox.kill()
> ```

> [!NOTE]
>
> Recursive watching (`recursive=True`) requires an up-to-date template. On an older template, the SDK raises a template error that asks for a rebuild. Rebuild the template with `ppio template build`. See [Errors](https://docs.ppio.ai/sandbox/errors.md).


## Related topics

- [Work with files in a sandbox](https://docs.ppio.ai/sandbox/filesystem/overview.md)
- [Get file and directory metadata](https://docs.ppio.ai/sandbox/filesystem/metadata.md)
- [Changelog](https://docs.ppio.ai/changelog.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.