跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

管理文件

最后更新 查看 MarkdownAgent 设置

本指南向您介绍如何在沙箱文件系统中读取、写入、组织和同步文件。

路径约定

文件操作同时支持绝对路径和相对路径:

  • /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');
  }
}

相关资源

这篇文档对您有帮助吗?