在 sandbox 文件系统中读取、写入与管理文件。所有路径均为绝对路径(例如 /workspace/app.js)。
将内容写入文件。
await sandbox.writeFile(path: string, content: string, options?: WriteFileOptions): Promise<void>参数:
path- 文件的绝对路径content- 要写入的内容options(可选):encoding- 文件编码("utf-8"或"base64",默认:"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' });使用 rpc 传输 时,writeFile() 方法支持将 ReadableStream 作为 content 参数传入。这样可将二进制数据以及大于 32 MiB 的文件写入 sandbox。它会取代 "base64" 编码选项。
// 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);从 sandbox 读取文件。默认以字符串形式返回内容,适用于小型文本文件。对于较大文件与二进制数据,请使用 encoding: "none" 以获取包含文件数据的 ReadableStream。
const file = await sandbox.readFile(path: string, options?: ReadFileOptions): Promise<ReadFileResult | ReadFileStreamResult>参数:
path- 文件的绝对路径options(可选):encoding- 文件编码("utf-8"、"base64"或"none",默认:根据 MIME 类型自动检测)
返回: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>";检查文件或目录是否存在。
const result = await sandbox.exists(path: string): Promise<FileExistsResult>参数:
path- 要检查的绝对路径
返回:带有 exists 布尔值的 Promise<FileExistsResult>
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');
}创建目录。
await sandbox.mkdir(path: string, options?: MkdirOptions): Promise<void>参数:
path- 目录的绝对路径options(可选):recursive- 在需要时创建父目录(默认: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 });删除文件。
await sandbox.deleteFile(path: string): Promise<void>参数:
path- 文件的绝对路径
await sandbox.deleteFile("/workspace/temp.txt");await sandbox.deleteFile('/workspace/temp.txt');重命名文件。
await sandbox.renameFile(oldPath: string, newPath: string): Promise<void>参数:
oldPath- 当前文件路径newPath- 新文件路径
await sandbox.renameFile("/workspace/draft.txt", "/workspace/final.txt");await sandbox.renameFile('/workspace/draft.txt', '/workspace/final.txt');将文件移动到不同目录。
await sandbox.moveFile(sourcePath: string, destinationPath: string): Promise<void>参数:
sourcePath- 当前文件路径destinationPath- 目标路径
await sandbox.moveFile("/tmp/download.txt", "/workspace/data.txt");await sandbox.moveFile('/tmp/download.txt', '/workspace/data.txt');克隆 git 仓库。
await sandbox.gitCheckout(repoUrl: string, options?: GitCheckoutOptions): Promise<void>参数:
repoUrl- Git 仓库 URLoptions(可选):branch- 要检出的分支(默认:仓库默认分支)targetDir- 克隆到的目录(默认:/workspace/{repoName})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,
});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
});- 管理文件指南 - 包含最佳实践的详细指南
- Commands API - 执行命令