You can watch a directory for changes using the files.watchDir() method in JavaScript and files.watch_dir() method in Python.
const sandbox = await Sandbox.create() const dirname = '/home/user'
// Start watching directory for changes
const handle = await sandbox.files.watchDir(dirname, async (event) => { // $HighlightLine
console.log(event) // $HighlightLine
if (event.type === FilesystemEventType.WRITE) { // $HighlightLine
console.log(wrote to file ${event.name}) // $HighlightLine
} // $HighlightLine
}) // $HighlightLine
// Trigger file write event
await sandbox.files.write(${dirname}/my-file, 'hello')
```python
from e2b_code_interpreter import Sandbox
sandbox = Sandbox.create()
dirname = '/home/user'
# Watch directory for changes
handle = sandbox.files.watch_dir(dirname) # $HighlightLine
# Trigger file write event
sandbox.files.write(f"{dirname}/my-file", "hello")
# Retrieve the latest new events since the last `get_new_events()` call
events = handle.get_new_events() # $HighlightLine
for event in events: # $HighlightLine
print(event) # $HighlightLine
if event.type == FilesystemEventType.Write: # $HighlightLine
print(f"wrote to file {event.name}") # $HighlightLine
You can enable recursive watching using the parameter recursive.
const sandbox = await Sandbox.create() const dirname = '/home/user'
// Start watching directory for changes
const handle = await sandbox.files.watchDir(dirname, async (event) => {
console.log(event)
if (event.type === FilesystemEventType.WRITE) {
console.log(wrote to file ${event.name})
}
}, {
recursive: true // $HighlightLine
})
// Trigger file write event
await sandbox.files.write(${dirname}/my-folder/my-file, 'hello') // $HighlightLine
```python
from e2b_code_interpreter import Sandbox
sandbox = Sandbox.create()
dirname = '/home/user'
# Watch directory for changes
handle = sandbox.files.watch_dir(dirname, recursive=True) # $HighlightLine
# Trigger file write event
sandbox.files.write(f"{dirname}/my-folder/my-file", "hello") # $HighlightLine
# Retrieve the latest new events since the last `get_new_events()` call
events = handle.get_new_events()
for event in events:
print(event)
if event.type == FilesystemEventType.Write:
print(f"wrote to file {event.name}")