Sandbox SDK Sandbox SDK Sandbox SDK · Lab 2/7 Lab 2/7 Lab 2/7 · 20 phút · 20 min · 20 នាទី

02

Lệnh lõi và file Core Commands & Files ពាក្យបញ្ជាគន្លឹះ និង file

Nắm exec(), writeFile(), readFile(), listFiles() qua ví dụ thực hành. Master the Sandbox SDK's core commands and file operations. Learn exec(), writeFile(), readFile(), and listFiles() with hands-on examples. យល់ exec(), writeFile(), readFile(), listFiles() តាមឧទាហរណ៍អនុវត្ត។

Nội dung bước (lệnh, code) giữ nguyên tiếng Anh từ nguồn chính thức. Step body (commands, code) stays in English from the official source. ខ្លឹមសារជំហាន (ពាក្យបញ្ជា និង code) រក្សាភាសាអង់គ្លេសពីប្រភពផ្លូវការ។ labs.cloudflare.dev ↗

Cần trước Prerequisites តម្រូវការជាមុន

  • Đã xong bước 1 Completed Step 1 បានបញ្ចប់ជំហាន 1
  • Sandbox đang chạy local Sandbox running locally Sandbox កំពុងរត់ local
  • Docker đang chạy Docker running Docker កំពុងរត់

Bạn sẽ làm được Learning objectives គោលបំណងសិក្សា

  • Chạy lệnh shell bằng exec() kèm options Execute shell commands using exec() with options រត់ពាក្យបញ្ជា shell ដោយ exec() ជាមួយ options
  • Thao tác file bằng writeFile(), readFile(), listFiles() Work with files using writeFile(), readFile(), and listFiles() ធ្វើការជាមួយ file ដោយ writeFile(), readFile(), listFiles()
  • Hiểu object kết quả của exec() Understand the exec() result object យល់ object លទ្ធផលរបស់ exec()
  • Kết hợp nhiều API trong một endpoint Combine multiple APIs in a single endpoint បញ្ចូល API ច្រើនក្នុង endpoint តែមួយ

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:

typescript
const result = await sandbox.exec(command: string, options?: ExecOptions);

The result object:

The result object:

The result object:

typescript
{
  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:

typescript
// 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:

typescript
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:

typescript
const file = await sandbox.readFile("/workspace/hello.txt");
console.log(file.content); // "Hello, Sandbox!"

mkdir() — create directories:

mkdir() — create directories:

mkdir() — create directories:

typescript
await sandbox.mkdir("/workspace/src");

// Create nested directories in one call
await sandbox.mkdir("/workspace/src/components/ui", { recursive: true });
typescript
await sandbox.exec("npm install", { cwd: "/workspace/my-app" });

listFiles() — list a directory:

listFiles() — list a directory:

listFiles() — list a directory:

typescript
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:

bash
curl http://localhost:8787/file
json
{
  "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:

typescript
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(...):

typescript
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:

bash
curl http://localhost:8787/custom
json
{
  "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:

typescript
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:

bash
curl -i http://localhost:8787/error
txt
{
  "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.