Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

ファイル

最終更新 Markdown で表示Agent セットアップ

サンドボックスのファイルシステムでファイルの読み書きと管理を行います。パスはすべて絶対パスです(例: /workspace/app.js)。

メソッド

writeFile()

ファイルに内容を書き込みます。

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()content パラメーターに ReadableStream を渡せます。バイナリデータと 32 MiB を超えるファイルをサンドボックスへ書き込めます。"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);

readFile()

サンドボックスからファイルを読み取ります。デフォルトでは内容を文字列で返します。小さなテキストファイルに向きます。大きなファイルとバイナリデータでは 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>";

exists()

ファイルまたはディレクトリの存在を確認します。

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

mkdir()

ディレクトリを作成します。

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 });

deleteFile()

ファイルを削除します。

await sandbox.deleteFile(path: string): Promise<void>

パラメーター:

  • path - ファイルの絶対パス
await sandbox.deleteFile("/workspace/temp.txt");
await sandbox.deleteFile('/workspace/temp.txt');

renameFile()

ファイルの名前を変更します。

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');

moveFile()

ファイルを別のディレクトリへ移動します。

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');

gitCheckout()

git リポジトリをクローンします。

await sandbox.gitCheckout(repoUrl: string, options?: GitCheckoutOptions): Promise<void>

パラメーター:

  • repoUrl - Git リポジトリの URL
  • options(任意):
    • 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
});

関連リソース

役に立ちましたか?