← Sandbox SDK / sandbox / api
Soubory
Čtěte, zapisujte a spravujte soubory v souborovém systému sandboxu. Všechny cesty jsou absolutní (např. /workspace/app.js).
Metody
writeFile()
Zapíše obsah do souboru.
await sandbox.writeFile(path: string, content: string, options?: WriteFileOptions): Promise<void>Parametry:
path- Absolutní cesta k souborucontent- Obsah k zápisuoptions(volitelné):encoding- Kódování souboru ("utf-8"nebo"base64", výchozí:"utf-8")
await sandbox.writeFile("/workspace/app.js", `console.log('Hello!');`);
// Binary data
await sandbox.writeFile("/tmp/image.png", base64Data, { encoding: "base64" });await sandbox.writeFile('/workspace/app.js', `console.log('Hello!');`);
// Binary data
await sandbox.writeFile('/tmp/image.png', base64Data, { encoding: 'base64' });Velké soubory a binární data
Při použití rpc přenos writeFile() metoda umožňuje předat ReadableStream jako content parametr. Díky tomu lze binární data a soubory větší než 32 MiB aby byl zapsán do sandboxu. Nahrazuje "base64" možnost encoding.
// Requires SANDBOX_TRANSPORT to be "rpc" in wrangler.jsonc
const req = await fetch("https://example.com/archive.tar.gz");
await sandbox.writeFile('/workspace/archive.tar.gz', req.body);readFile()
Přečtěte soubor ze sandboxu. Ve výchozím nastavení vrací obsah jako řetězec (string), což se hodí pro malé textové soubory. Pro větší soubory a binární data použijte encoding: "none" pro získání ReadableStream s daty souboru.
const file = await sandbox.readFile(path: string, options?: ReadFileOptions): Promise<ReadFileResult | ReadFileStreamResult>Parametry:
path- Absolutní cesta k souboruoptions(volitelné):encoding- Kódování souboru ("utf-8","base64"nebo"none", výchozí: automaticky rozpoznáno podle typu MIME)
Vrací: Promise<ReadFileResult | ReadFileStreamResult>.
const file = await sandbox.readFile("/workspace/package.json");
const pkg = JSON.parse(file.content);
// Binary data (since 0.10.1 using `rpc` transport)
const { content, size, mimeType } = await sandbox.readFile(
"/workspace/archive.tar.gz",
{
encoding: "none",
},
);
// Example 1: Store on R2:
const stream = request.body.pipeThrough(new FixedLengthStream(size));
await env.MY_BUCKET.put("/bucket/archive.tar.gz", stream, {
httpMetadata: { contentType: mimeType },
});
// Example 2: Stream an HTTP response:
return new Response(content, { headers: { "Content-Type": mimeType } });
// Older versions/transports used the base64 encoding for binary data:
const archive = await sandbox.readFile("/workspace/archive.tar.gz", {
encoding: "base64",
});
console.log(archive.content); // => "<base64 encoded string>";const file = await sandbox.readFile('/workspace/package.json');
const pkg = JSON.parse(file.content);
// Binary data (since 0.10.1 using `rpc` transport)
const { content, size, mimeType } = await sandbox.readFile("/workspace/archive.tar.gz", {
encoding: "none"
});
// Example 1: Store on R2:
const stream = request.body.pipeThrough(new FixedLengthStream(size));
await env.MY_BUCKET.put('/bucket/archive.tar.gz', stream, {
httpMetadata: { contentType: mimeType }
});
// Example 2: Stream an HTTP response:
return new Response(content, { headers: { "Content-Type": mimeType } });
// Older versions/transports used the base64 encoding for binary data:
const archive = await sandbox.readFile("/workspace/archive.tar.gz", {
encoding: "base64"
});
console.log(archive.content); // => "<base64 encoded string>";exists()
Zkontrolujte, zda soubor nebo adresář existuje.
const result = await sandbox.exists(path: string): Promise<FileExistsResult>Parametry:
path- Absolutní cesta ke kontrole
Vrací: Promise<FileExistsResult> hodnotou exists boolean
const result = await sandbox.exists("/workspace/package.json");
if (result.exists) {
const file = await sandbox.readFile("/workspace/package.json");
// process file
}
// Check directory
const dirResult = await sandbox.exists("/workspace/src");
if (!dirResult.exists) {
await sandbox.mkdir("/workspace/src");
}const result = await sandbox.exists('/workspace/package.json');
if (result.exists) {
const file = await sandbox.readFile('/workspace/package.json');
// process file
}
// Check directory
const dirResult = await sandbox.exists('/workspace/src');
if (!dirResult.exists) {
await sandbox.mkdir('/workspace/src');
}mkdir()
Vytvořte adresář.
await sandbox.mkdir(path: string, options?: MkdirOptions): Promise<void>Parametry:
path- Absolutní cesta k adresářioptions(volitelné):recursive- V případě potřeby vytvořte nadřazené adresáře (výchozí:false)
await sandbox.mkdir("/workspace/src");
// Nested directories
await sandbox.mkdir("/workspace/src/components/ui", { recursive: true });await sandbox.mkdir('/workspace/src');
// Nested directories
await sandbox.mkdir('/workspace/src/components/ui', { recursive: true });deleteFile()
Odstraní soubor.
await sandbox.deleteFile(path: string): Promise<void>Parametry:
path- Absolutní cesta k souboru
await sandbox.deleteFile("/workspace/temp.txt");await sandbox.deleteFile('/workspace/temp.txt');renameFile()
Přejmenuje soubor.
await sandbox.renameFile(oldPath: string, newPath: string): Promise<void>Parametry:
oldPath- Aktuální cesta k souborunewPath- Nová cesta k souboru
await sandbox.renameFile("/workspace/draft.txt", "/workspace/final.txt");await sandbox.renameFile('/workspace/draft.txt', '/workspace/final.txt');moveFile()
Přesuňte soubor do jiného adresáře.
await sandbox.moveFile(sourcePath: string, destinationPath: string): Promise<void>Parametry:
sourcePath- Aktuální cesta k souborudestinationPath- Cílová cesta
await sandbox.moveFile("/tmp/download.txt", "/workspace/data.txt");await sandbox.moveFile('/tmp/download.txt', '/workspace/data.txt');gitCheckout()
Naklonujte repozitář Git.
await sandbox.gitCheckout(repoUrl: string, options?: GitCheckoutOptions): Promise<void>Parametry:
repoUrl- URL adresa repozitáře Gitoptions(volitelné):branch- Větev k přepnutí (výchozí: výchozí větev repozitáře)targetDir- Adresář, do kterého se má klonovat (výchozí:/workspace/{repoName})depth- Hloubka klonování pro mělké klony (např.1pouze pro nejnovější commit)
await sandbox.gitCheckout("https://github.com/user/repo");
// Specific branch
await sandbox.gitCheckout("https://github.com/user/repo", {
branch: "develop",
targetDir: "/workspace/my-project",
});
// Shallow clone (faster for large repositories)
await sandbox.gitCheckout("https://github.com/facebook/react", {
depth: 1,
});await sandbox.gitCheckout('https://github.com/user/repo');
// Specific branch
await sandbox.gitCheckout('https://github.com/user/repo', {
branch: 'develop',
targetDir: '/workspace/my-project'
});
// Shallow clone (faster for large repositories)
await sandbox.gitCheckout('https://github.com/facebook/react', {
depth: 1
});Související zdroje
- Průvodce správou souborů - Podrobný průvodce s doporučenými postupy
- Commands API - Spouštění příkazů