Manage files
Last updated Sep 30, 2026 Note
This page documents Sandbox SDK 0.x for existing applications. For new applications, refer to Move files in and out of a sandbox. To move an existing application to @cloudflare/sandbox 1.0, refer to Migrate from Sandbox SDK 0.x.
This guide shows you how to read, write, organize, and synchronize files in the sandbox filesystem.
Path conventions
File operations support both absolute and relative paths:
/workspace- Default working directory for application files/tmp- Temporary files (may be cleared)/home- User home directory
// Absolute paths
await sandbox.writeFile("/workspace/app.js", code);
// Relative paths (session-aware)
const session = await sandbox.createSession();
await session.exec("cd /workspace/my-project");
await session.writeFile("app.js", code); // Writes to /workspace/my-project/app.js
await session.writeFile("src/index.js", code); // Writes to /workspace/my-project/src/index.js
// Absolute paths
await sandbox.writeFile('/workspace/app.js', code);
// Relative paths (session-aware)
const session = await sandbox.createSession();
await session.exec('cd /workspace/my-project');
await session.writeFile('app.js', code); // Writes to /workspace/my-project/app.js
await session.writeFile('src/index.js', code); // Writes to /workspace/my-project/src/index.js
Write files
import { getSandbox } from "@cloudflare/sandbox";
const sandbox = getSandbox(env.Sandbox, "my-sandbox");
// Write text file
await sandbox.writeFile(
"/workspace/app.js",
`console.log('Hello from sandbox!');`,
);
// Write JSON
const config = { name: "my-app", version: "1.0.0" };
await sandbox.writeFile(
"/workspace/config.json",
JSON.stringify(config, null, 2),
);
// Write binary file (base64)
const buffer = await fetch(imageUrl).then((r) => r.arrayBuffer());
const base64 = btoa(String.fromCharCode(...new Uint8Array(buffer)));
await sandbox.writeFile("/workspace/image.png", base64, { encoding: "base64" });
import { getSandbox } from '@cloudflare/sandbox';
const sandbox = getSandbox(env.Sandbox, 'my-sandbox');
// Write text file
await sandbox.writeFile('/workspace/app.js', `console.log('Hello from sandbox!');`);
// Write JSON
const config = { name: 'my-app', version: '1.0.0' };
await sandbox.writeFile('/workspace/config.json', JSON.stringify(config, null, 2));
// Write binary file (base64)
const buffer = await fetch(imageUrl).then(r => r.arrayBuffer());
const base64 = btoa(String.fromCharCode(...new Uint8Array(buffer)));
await sandbox.writeFile('/workspace/image.png', base64, { encoding: 'base64' });
Read files
// Read text file
const file = await sandbox.readFile("/workspace/app.js");
console.log(file.content);
// Read and parse JSON
const configFile = await sandbox.readFile("/workspace/config.json");
const config = JSON.parse(configFile.content);
// Read binary file (v0.10.1 with `rpc` transport)
const imageFile = await sandbox.readFile("/workspace/image.png", {
encoding: "none",
});
return new Response(imageFile.content, {
headers: { "Content-Type": imageFile.mimeType },
});
// Read text file
const file = await sandbox.readFile('/workspace/app.js');
console.log(file.content);
// Read and parse JSON
const configFile = await sandbox.readFile('/workspace/config.json');
const config = JSON.parse(configFile.content);
// Read binary file (v0.10.1 with `rpc` transport)
const imageFile = await sandbox.readFile('/workspace/image.png', { encoding: 'none' });
return new Response(imageFile.content, {
headers: { 'Content-Type': imageFile.mimeType }
});
Note
For more details on the rpc transport please see the Transport docs.
Organize files
// Create directories
await sandbox.mkdir("/workspace/src", { recursive: true });
await sandbox.mkdir("/workspace/tests", { recursive: true });
// Rename file
await sandbox.renameFile("/workspace/draft.txt", "/workspace/final.txt");
// Move file
await sandbox.moveFile("/tmp/download.txt", "/workspace/data.txt");
// Delete file
await sandbox.deleteFile("/workspace/temp.txt");
// Create directories
await sandbox.mkdir('/workspace/src', { recursive: true });
await sandbox.mkdir('/workspace/tests', { recursive: true });
// Rename file
await sandbox.renameFile('/workspace/draft.txt', '/workspace/final.txt');
// Move file
await sandbox.moveFile('/tmp/download.txt', '/workspace/data.txt');
// Delete file
await sandbox.deleteFile('/workspace/temp.txt');
Batch operations
Write multiple files in parallel:
const files = {
"/workspace/src/app.js": 'console.log("app");',
"/workspace/src/utils.js": 'console.log("utils");',
"/workspace/README.md": "# My Project",
};
await Promise.all(
Object.entries(files).map(([path, content]) =>
sandbox.writeFile(path, content),
),
);
const files = {
'/workspace/src/app.js': 'console.log("app");',
'/workspace/src/utils.js': 'console.log("utils");',
'/workspace/README.md': '# My Project'
};
await Promise.all(
Object.entries(files).map(([path, content]) =>
sandbox.writeFile(path, content)
)
);
Check if file exists
const result = await sandbox.exists("/workspace/config.json");
if (!result.exists) {
// Create default config
await sandbox.writeFile("/workspace/config.json", "{}");
}
// Check directory
const dirResult = await sandbox.exists("/workspace/data");
if (!dirResult.exists) {
await sandbox.mkdir("/workspace/data");
}
// Also available on sessions
const sessionResult = await session.exists("/workspace/temp.txt");
const result = await sandbox.exists('/workspace/config.json');
if (!result.exists) {
// Create default config
await sandbox.writeFile('/workspace/config.json', '{}');
}
// Check directory
const dirResult = await sandbox.exists('/workspace/data');
if (!dirResult.exists) {
await sandbox.mkdir('/workspace/data');
}
// Also available on sessions
const sessionResult = await session.exists('/workspace/temp.txt');
Best practices
- Use
/workspace- Default working directory for app files - Use absolute paths - Always use full paths like
/workspace/file.txt - Batch operations - Use
Promise.all()for multiple independent file writes - Create parent directories - Use
recursive: truewhen creating nested paths - Handle errors - Check for
FILE_NOT_FOUNDerrors gracefully
Troubleshooting
Directory doesn't exist
Create parent directories first:
// Create directory, then write file
await sandbox.mkdir("/workspace/data", { recursive: true });
await sandbox.writeFile("/workspace/data/file.txt", content);
// Create directory, then write file
await sandbox.mkdir('/workspace/data', { recursive: true });
await sandbox.writeFile('/workspace/data/file.txt', content);
Binary file encoding
Use encoding: "none" (with rpc transport) for binary files:
// Write binary
await sandbox.writeFile("/workspace/image.png", readableStream);
// Read binary
const file = await sandbox.readFile("/workspace/image.png", {
encoding: "none",
});
// Write binary
await sandbox.writeFile('/workspace/image.png', readableStream);
// Read binary
const file = await sandbox.readFile('/workspace/image.png', {
encoding: 'none'
});
For older SDK versions or http transport:
// Write binary
await sandbox.writeFile("/workspace/image.png", base64data, {
encoding: "base64",
});
// Read binary
const file = await sandbox.readFile("/workspace/image.png", {
encoding: "base64",
});
// Write binary
await sandbox.writeFile('/workspace/image.png', base64data, { encoding: "base64" });
// Read binary
const file = await sandbox.readFile('/workspace/image.png', {
encoding: 'base64'
});
Base64 validation errors
When writing with encoding: 'base64', content must contain only valid base64 characters:
try {
// Invalid: contains invalid base64 characters
await sandbox.writeFile("/workspace/data.bin", "invalid!@#$", {
encoding: "base64",
});
} catch (error) {
if (error.code === "VALIDATION_FAILED") {
// Content contains invalid base64 characters
console.error("Invalid base64 content");
}
}
try {
// Invalid: contains invalid base64 characters
await sandbox.writeFile('/workspace/data.bin', 'invalid!@#$', {
encoding: 'base64'
});
} catch (error) {
if (error.code === 'VALIDATION_FAILED') {
// Content contains invalid base64 characters
console.error('Invalid base64 content');
}
}
Related resources
- Files API reference - Complete method documentation
- Execute commands guide - Run file operations with commands
- Git workflows guide - Clone and manage repositories
- Code Interpreter guide - Generate and execute code files
Was this helpful?
YesNo
On this page
{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/sandbox/sdk/guides/manage-files/#page","headline":"Manage files","description":"Read, write, organize, and synchronize files in a sandbox with the Sandbox SDK 0.x.","url":"https://developers.cloudflare.com/sandbox/sdk/guides/manage-files/","inLanguage":"en","image":"https://developers.cloudflare.com/sandbox/sdk/guides/manage-files/og.png?v=2d65d3edba18b16f","dateModified":"2026-09-30","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}
description: Mount S3-compatible object storage as local filesystems with the Sandbox SDK 0.x. title: Mount buckets image: https://developers.cloudflare.com/sandbox/sdk/guides/mount-buckets/og.png?v=546520f95679accb
Documentation Index
Fetch the complete documentation index at: https://developers.cloudflare.com/sandbox/llms.txt
Use this file to discover all available pages before exploring further.
Docs