Skip to main content
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

command
string
required
Shell command to execute. Runs in a bash shell with full shell features.
options
StreamOptions
Execution options

Returns

AsyncIterable<ExecEvent>
async iterable
An async iterable that yields execution events as they occur

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

Build docs developers (and LLMs) love