Bước 1: API exec() Step 1: The exec() API ជំហាន 1: API exec()
- Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
- Mastery of exec() — the fundamental API for running commands in your sandbox.
- Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
- exec() is the building block for everything from installing packages to running scripts to executing AI-generated code.
exec() runs a shell command inside the container and returns a structured result:
exec() runs a shell command inside the container and returns a structured result:
exec() runs a shell command inside the container and returns a structured result:
const result = await sandbox.exec(command: string, options?: ExecOptions); The result object:
The result object:
The result object:
{
stdout: string; // Standard output from the command
stderr: string; // Standard error output
exitCode: number; // 0 = success, non-zero = failure
success: boolean; // true when exitCode === 0
} exec() with options:
exec() with options:
exec() with options:
// Simple command
const result = await sandbox.exec('echo "Hello Sandbox"');
// With working directory
const result = await sandbox.exec("npm install", {
cwd: "/workspace/my-app",
});
// With environment variables
const result = await sandbox.exec("node app.js", {
env: { NODE_ENV: "production", PORT: "3000" },
});
// With timeout (ms)
const result = await sandbox.exec("npm test", {
timeout: 60000, // 60 seconds
});
// With stdin — pass data to the command's standard input (avoids shell injection)
const result = await sandbox.exec("cat", {
stdin: "Hello from stdin!",
});
console.log(result.stdout); // "Hello from stdin!" Bước 2: Thao tác file Step 2: File Operations ជំហាន 2: ប្រតិបត្តិការ file
- Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
- Ability to read, write, and list files in the sandbox filesystem.
- Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
- Most real code execution workflows require creating input files, reading output files, or both.
The file APIs map directly to what you’d expect:
The file APIs map directly to what you’d expect:
The file APIs map directly to what you’d expect:
writeFile() — create or overwrite a file:
writeFile() — create or overwrite a file:
writeFile() — create or overwrite a file:
await sandbox.writeFile("/workspace/hello.txt", "Hello, Sandbox!");
await sandbox.writeFile(
"/workspace/app.js",
'console.log("Hello from sandbox")',
); readFile() — read a file’s contents:
readFile() — read a file’s contents:
readFile() — read a file’s contents:
const file = await sandbox.readFile("/workspace/hello.txt");
console.log(file.content); // "Hello, Sandbox!" mkdir() — create directories:
mkdir() — create directories:
mkdir() — create directories:
await sandbox.mkdir("/workspace/src");
// Create nested directories in one call
await sandbox.mkdir("/workspace/src/components/ui", { recursive: true }); await sandbox.exec("npm install", { cwd: "/workspace/my-app" }); listFiles() — list a directory:
listFiles() — list a directory:
listFiles() — list a directory:
const entries = await sandbox.listFiles("/workspace");
// Returns an array of { name, type, size, ... } Now test the /file endpoint that already exists in your template:
Now test the /file endpoint that already exists in your template:
Now test the /file endpoint that already exists in your template:
curl http://localhost:8787/file {
"content": "Hello, Sandbox!"
} Open src/index.ts and find the /file handler to understand the code:
Open src/index.ts and find the /file handler to understand the code:
Open src/index.ts and find the /file handler to understand the code:
if (url.pathname === "/file") {
await sandbox.writeFile("/workspace/hello.txt", "Hello, Sandbox!");
const file = await sandbox.readFile("/workspace/hello.txt");
return Response.json({
content: file.content,
files: await sandbox.listFiles("/workspace"),
});
} Bước 3: Viết endpoint tùy chỉnh Step 3: Build a Custom Endpoint ជំហាន 3: សរសេរ endpoint ផ្ទាល់ខ្លួន
- Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
- A new /custom endpoint that combines exec() and file operations in a real workflow.
- Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
- Real applications chain multiple APIs together — writing a script, making it executable, and running it.
Add this handler to src/index.ts, before the final return new Response(...):
Add this handler to src/index.ts, before the final return new Response(...):
Add this handler to src/index.ts, before the final return new Response(...):
if (url.pathname === "/custom") {
// Write a shell script into the sandbox
await sandbox.writeFile(
"/workspace/info.sh",
`#!/bin/bash
echo "=== Sandbox Info ==="
echo "Date: $(date)"
echo "User: $(whoami)"
echo "Directory: $(pwd)"
echo "Node version: $(node --version)"
echo "Files in /workspace:"
ls /workspace
`,
);
// Make it executable and run it
await sandbox.exec("chmod +x /workspace/info.sh");
const result = await sandbox.exec("/workspace/info.sh");
return Response.json({
output: result.stdout,
success: result.success,
});
} Test it:
Test it:
Test it:
curl http://localhost:8787/custom {
"output": "=== Sandbox Info ===\nDate: Mon Jan 27 10:00:00 UTC 2025\nUser: root\nDirectory: /\nNode version: v20.x.x\nFiles in /workspace:\nhello.txt info.sh\n",
"success": true
} Bước 4: Xử lý lỗi từ exec() Step 4: Handle Errors from exec() ជំហាន 4: ដោះស្រាយ error ពី exec()
- Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
- Proper handling of command failures using the exec() result object.
- Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
- Commands can fail — checking exitCode and stderr is essential for reliable applications.
Add an endpoint that demonstrates error handling:
Add an endpoint that demonstrates error handling:
Add an endpoint that demonstrates error handling:
if (url.pathname === "/error") {
// Run a command that will fail
const result = await sandbox.exec("cat /workspace/nonexistent-file.txt");
if (!result.success) {
return Response.json(
{
success: false,
error: result.stderr,
exitCode: result.exitCode,
},
{ status: 422 },
);
}
return Response.json({ content: result.stdout });
} Test it:
Test it:
Test it:
curl -i http://localhost:8787/error {
"success": false,
"error": "cat: /workspace/nonexistent-file.txt: No such file or directory\n",
"exitCode": 1
} ✅ Core APIs mastered! You can now execute commands and work with the sandbox filesystem. Next, you’ll use the higher-level runCode() API to build a full code interpreter.
✅ Core APIs mastered! You can now execute commands and work with the sandbox filesystem. Next, you’ll use the higher-level runCode() API to build a full code interpreter.
✅ Core APIs mastered! You can now execute commands and work with the sandbox filesystem. Next, you’ll use the higher-level runCode() API to build a full code interpreter.