Executes a shell command and streams the output as it’s produced. Returns an async iterable of execution events.
Method Signature
sandbox.execStream(
command: string,
options?: StreamOptions
): AsyncIterable<ExecEvent>
Parameters
Shell command to execute. Runs in a bash shell with full shell features.
Execution options
Maximum execution time in milliseconds
Environment variables for this command
Working directory for the command
Returns
An async iterable that yields execution events as they occur
Standard output chunk
text: string - Output text
Standard error chunk
text: string - Error text
Command completion
exitCode: number - Exit code
Examples
Stream command output
for await (const event of sandbox.execStream('npm install')) {
if (event.type === 'stdout') {
console.log('[OUT]', event.text);
} else if (event.type === 'stderr') {
console.error('[ERR]', event.text);
} else if (event.type === 'exit') {
console.log('Exit code:', event.exitCode);
}
}
Stream long-running build
const events = sandbox.execStream('npm run build');
for await (const event of events) {
if (event.type === 'stdout') {
// Send build progress to client
await sendProgressUpdate(event.text);
}
}
Collect all output
let stdout = '';
let stderr = '';
for await (const event of sandbox.execStream('python script.py')) {
if (event.type === 'stdout') stdout += event.text;
if (event.type === 'stderr') stderr += event.text;
}
console.log('Full output:', stdout);
Stream with timeout
try {
for await (const event of sandbox.execStream('long-task', {
timeout: 60000
})) {
console.log(event);
}
} catch (error) {
console.error('Command timed out');
}
Stream to HTTP response
export default {
async fetch(request: Request, env: Env) {
const sandbox = getSandbox(env.Sandbox, 'my-sandbox');
const stream = new ReadableStream({
async start(controller) {
for await (const event of sandbox.execStream('tail -f log.txt')) {
if (event.type === 'stdout') {
controller.enqueue(new TextEncoder().encode(event.text));
}
}
controller.close();
}
});
return new Response(stream, {
headers: { 'Content-Type': 'text/plain' }
});
}
};
Use Cases
- Build pipelines with progress updates
- Log tailing and monitoring
- Long-running data processing
- Real-time command output in UI
- Streaming responses to clients