Commands
Execute commands and manage background processes in the sandbox's isolated container environment.
Execute a command and return the complete result.
const result = await sandbox.exec(command: string, options?: ExecOptions): Promise<ExecuteResponse>Parameters:
command- The command to execute (can include arguments)options(optional):stream- Enable streaming callbacks (default:false)onOutput- Callback for real-time output:(stream: 'stdout' | 'stderr', data: string) => voidtimeout- Maximum execution time in milliseconds
Returns: Promise<ExecuteResponse> with success, stdout, stderr, exitCode
const result = await sandbox.exec("npm run build");
if (result.success) { console.log("Build output:", result.stdout);} else { console.error("Build failed:", result.stderr);}
// With streamingawait sandbox.exec("npm install", { stream: true, onOutput: (stream, data) => console.log(`[${stream}] ${data}`),});const result = await sandbox.exec('npm run build');
if (result.success) { console.log('Build output:', result.stdout);} else { console.error('Build failed:', result.stderr);}
// With streamingawait sandbox.exec('npm install', { stream: true, onOutput: (stream, data) => console.log(`[${stream}] ${data}`)});Execute a command and return a Server-Sent Events stream for real-time processing.
const stream = await sandbox.execStream(command: string, options?: ExecOptions): Promise<ReadableStream>Parameters:
command- The command to executeoptions- Same asexec()
Returns: Promise<ReadableStream> emitting ExecEvent objects (start, stdout, stderr, complete, error)
import { parseSSEStream } from "@cloudflare/sandbox";
const stream = await sandbox.execStream("npm run build");
for await (const event of parseSSEStream(stream)) { switch (event.type) { case "stdout": console.log("Output:", event.data); break; case "complete": console.log("Exit code:", event.exitCode); break; case "error": console.error("Failed:", event.error); break; }}import { parseSSEStream, type ExecEvent } from '@cloudflare/sandbox';
const stream = await sandbox.execStream('npm run build');
for await (const event of parseSSEStream<ExecEvent>(stream)) { switch (event.type) { case 'stdout': console.log('Output:', event.data); break; case 'complete': console.log('Exit code:', event.exitCode); break; case 'error': console.error('Failed:', event.error); break; }}Start a long-running background process.
const process = await sandbox.startProcess(command: string, options?: ProcessOptions): Promise<Process>Parameters:
command- The command to start as a background processoptions(optional):cwd- Working directoryenv- Environment variables
Returns: Promise<Process> object with:
id- Unique process identifierpid- System process IDcommand- The command being executedstatus- Current status ('running','exited', etc.)kill()- Stop the processgetStatus()- Get current statusgetLogs()- Get accumulated logswaitForPort()- Wait for process to listen on a portwaitForLog()- Wait for pattern in process output
const server = await sandbox.startProcess("python -m http.server 8000");console.log("Started with PID:", server.pid);
// With custom environmentconst app = await sandbox.startProcess("node app.js", { cwd: "/workspace/my-app", env: { NODE_ENV: "production", PORT: "3000" },});const server = await sandbox.startProcess('python -m http.server 8000');console.log('Started with PID:', server.pid);
// With custom environmentconst app = await sandbox.startProcess('node app.js', { cwd: '/workspace/my-app', env: { NODE_ENV: 'production', PORT: '3000' }});List all running processes.
const processes = await sandbox.listProcesses(): Promise<ProcessInfo[]>const processes = await sandbox.listProcesses();
for (const proc of processes) { console.log(`${proc.id}: ${proc.command} (PID ${proc.pid})`);}const processes = await sandbox.listProcesses();
for (const proc of processes) { console.log(`${proc.id}: ${proc.command} (PID ${proc.pid})`);}Terminate a specific process.
await sandbox.killProcess(processId: string, signal?: string): Promise<void>Parameters:
processId- The process ID (fromstartProcess()orlistProcesses())signal- Signal to send (default:"SIGTERM")
const server = await sandbox.startProcess("python -m http.server 8000");await sandbox.killProcess(server.id);const server = await sandbox.startProcess('python -m http.server 8000');await sandbox.killProcess(server.id);Terminate all running processes.
await sandbox.killAllProcesses(): Promise<void>await sandbox.killAllProcesses();await sandbox.killAllProcesses();Stream logs from a running process in real-time.
const stream = await sandbox.streamProcessLogs(processId: string): Promise<ReadableStream>Parameters:
processId- The process ID
Returns: Promise<ReadableStream> emitting LogEvent objects
import { parseSSEStream } from "@cloudflare/sandbox";
const server = await sandbox.startProcess("node server.js");const logStream = await sandbox.streamProcessLogs(server.id);
for await (const log of parseSSEStream(logStream)) { console.log(`[${log.timestamp}] ${log.data}`);
if (log.data.includes("Server started")) break;}import { parseSSEStream, type LogEvent } from '@cloudflare/sandbox';
const server = await sandbox.startProcess('node server.js');const logStream = await sandbox.streamProcessLogs(server.id);
for await (const log of parseSSEStream<LogEvent>(logStream)) { console.log(`[${log.timestamp}] ${log.data}`);
if (log.data.includes('Server started')) break;}Get accumulated logs from a process.
const logs = await sandbox.getProcessLogs(processId: string): Promise<string>Parameters:
processId- The process ID
Returns: Promise<string> with all accumulated output
const server = await sandbox.startProcess("node server.js");await new Promise((resolve) => setTimeout(resolve, 5000));
const logs = await sandbox.getProcessLogs(server.id);console.log("Server logs:", logs);const server = await sandbox.startProcess('node server.js');await new Promise(resolve => setTimeout(resolve, 5000));
const logs = await sandbox.getProcessLogs(server.id);console.log('Server logs:', logs);The Process object returned by startProcess() includes methods to wait for the process to be ready before proceeding.
Wait for a process to listen on a port.
await process.waitForPort(port: number, options?: WaitForPortOptions): Promise<void>Parameters:
port- The port number to checkoptions(optional):mode- Check mode:'http'(default) or'tcp'timeout- Maximum wait time in millisecondsinterval- Check interval in milliseconds (default:100)path- HTTP path to check (default:'/', HTTP mode only)status- Expected HTTP status range (default:{ min: 200, max: 399 }, HTTP mode only)
HTTP mode (default) makes an HTTP GET request and checks the response status:
const server = await sandbox.startProcess("node server.js");
// Wait for server to be ready (HTTP mode)await server.waitForPort(3000);
// Check specific endpoint and statusawait server.waitForPort(8080, { path: "/health", status: { min: 200, max: 299 }, timeout: 30000,});const server = await sandbox.startProcess('node server.js');
// Wait for server to be ready (HTTP mode)await server.waitForPort(3000);
// Check specific endpoint and statusawait server.waitForPort(8080, { path: '/health', status: { min: 200, max: 299 }, timeout: 30000});TCP mode checks if the port accepts connections:
const db = await sandbox.startProcess("redis-server");
// Wait for database to accept connectionsawait db.waitForPort(6379, { mode: "tcp", timeout: 10000,});const db = await sandbox.startProcess('redis-server');
// Wait for database to accept connectionsawait db.waitForPort(6379, { mode: 'tcp', timeout: 10000});Throws:
ProcessReadyTimeoutError- If port does not become ready within timeoutProcessExitedBeforeReadyError- If process exits before becoming ready
Wait for a pattern to appear in process output.
const result = await process.waitForLog(pattern: string | RegExp, timeout?: number): Promise<WaitForLogResult>Parameters:
pattern- String or RegExp to match in stdout/stderrtimeout- Maximum wait time in milliseconds (optional)
Returns: Promise<WaitForLogResult> with:
line- The matching line of outputmatches- Array of capture groups (for RegExp patterns)
const server = await sandbox.startProcess("node server.js");
// Wait for string patternconst result = await server.waitForLog("Server listening");console.log("Ready:", result.line);
// Wait for RegExp with capture groupsconst result = await server.waitForLog(/Server listening on port (\d+)/);console.log("Port:", result.matches[1]); // Extracted port number
// With timeoutawait server.waitForLog("Ready", 30000);const server = await sandbox.startProcess('node server.js');
// Wait for string patternconst result = await server.waitForLog('Server listening');console.log('Ready:', result.line);
// Wait for RegExp with capture groupsconst result = await server.waitForLog(/Server listening on port (\d+)/);console.log('Port:', result.matches[1]); // Extracted port number
// With timeoutawait server.waitForLog('Ready', 30000);Throws:
ProcessReadyTimeoutError- If pattern is not found within timeoutProcessExitedBeforeReadyError- If process exits before pattern appears
- Background processes guide - Managing long-running processes
- Files API - File operations
Was this helpful?
- Resources
- API
- New to Cloudflare?
- Directory
- Sponsorships
- Open Source
- Support
- Help Center
- System Status
- Compliance
- GDPR
- Company
- cloudflare.com
- Our team
- Careers
- © 2025 Cloudflare, Inc.
- Privacy Policy
- Terms of Use
- Report Security Issues
- Trademark
-