← Sandbox SDK / sandbox / guides
Управление файлами
В этом руководстве показано, как читать, записывать, упорядочивать и синхронизировать файлы в файловой системе песочницы.
Соглашения о путях
Файловые операции поддерживают как абсолютные, так и относительные пути:
/workspace- Рабочий каталог по умолчанию для файлов приложения/tmp- Временные файлы (могут быть удалены)/home- Домашний каталог пользователя
// 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Запись файлов
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 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 }
});Организация файлов
// 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');Пакетные операции
Запись нескольких файлов параллельно:
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)
)
);Проверка существования файла
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');Рекомендации
- Используйте
/workspace- Рабочий каталог по умолчанию для файлов приложения - Используйте абсолютные пути - Всегда используйте полные пути, например
/workspace/file.txt - Пакетные операции - Используйте
Promise.all()для нескольких независимых операций записи файлов - Создайте родительские каталоги - Используйте
recursive: trueпри создании вложенных путей - Обработка ошибок - Проверьте наличие
FILE_NOT_FOUNDошибки корректно
Устранение неполадок
Каталог не существует
Сначала создайте родительские каталоги:
// 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);Кодировка бинарных файлов
Используйте encoding: "none" (с rpc транспорт) для бинарных файлов:
// 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'
});Для более старых версий SDK или http транспорт:
// 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
При записи с помощью encoding: 'base64', содержимое должно состоять только из допустимых символов base64:
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');
}
}Дополнительные материалы
- Справочник по Files API - Полная документация по методу
- Руководство по выполнению команд - Выполнение файловых операций с помощью команд
- Руководство по рабочим процессам Git - Клонируйте репозитории и управляйте ими
- Руководство по Code Interpreter - Создавайте и выполняйте файлы с кодом