Overview
The Sandbox SDK provides file operations that let you write and read both text and binary files within your sandboxes. This enables you to:- Create and execute scripts dynamically
- Store and retrieve data
- Work with configuration files
- Handle binary assets like images
Prerequisites
Before working with files, ensure you have:- Installed the Sandbox SDK (see Quickstart)
- Created a sandbox instance
- Basic familiarity with async/await in JavaScript/TypeScript
Writing Text Files
Usesandbox.files.write() to create or overwrite files with text content.
Basic Syntax
Example: Writing a JavaScript File
The response includes
bytesWritten and path to confirm the operation succeeded.Response Object
Reading Text Files
Usesandbox.files.read() to retrieve file contents as a string.
Basic Syntax
Example: Reading and Parsing JSON
By default,
read() returns text content as a string. For binary files, specify the encoding option (see below).Working with Binary Files
The SDK supports binary file operations usingUint8Array for writing and the encoding: "binary" option for reading.
Writing Binary Data
Reading Binary Data
Complete Workflow Example
Here’s a complete example that demonstrates writing a script, executing it, and reading the generated output:This example demonstrates the complete cycle: write → execute → read → verify.
Working with Relative Paths
File operations support relative paths withsandbox.cwd():
- The
cwdoption if provided - The persistent
sandbox.cwd()if set - The sandbox default directory (usually
/)
Best Practices
Error Handling
Wrap file operations in try-catch blocks to handle errors gracefully:Common errors include file not found, permission denied, or exceeding the 10 MB size limit.