Skip to main content

Description

Writes content to a file in the sandbox filesystem. Creates the file if it doesn’t exist, or overwrites it if it does.

Method Signature

async writeFile(
  path: string,
  content: string,
  options?: { encoding?: string; sessionId?: string }
): Promise<WriteFileResult>

Parameters

path
string
required
Absolute path where the file should be written
content
string
required
Content to write to the file
options
object
Optional configuration for the write operation
encoding
string
Encoding to use for writing the file (e.g., ‘utf-8’, ‘base64’)
sessionId
string
Session ID to use for this operation. If not provided, the default session is used.

Returns

WriteFileResult
object
Result of the write operation
success
boolean
Whether the file was written successfully
path
string
Path to the file that was written
timestamp
string
ISO 8601 timestamp of when the operation completed
exitCode
number
Exit code from the underlying write command (0 = success)

Examples

Write a text file

const result = await sandbox.writeFile(
  '/workspace/hello.txt',
  'Hello, Sandbox!'
);
console.log(result.success); // true

Write JSON data

const data = { name: 'John', age: 30 };
await sandbox.writeFile(
  '/workspace/data.json',
  JSON.stringify(data, null, 2)
);

Write with custom encoding

const base64Image = 'iVBORw0KGgoAAAANSUhEUgAAAAUA...';
await sandbox.writeFile('/workspace/image.png', base64Image, {
  encoding: 'base64'
});

Write to a specific session

const session = await sandbox.createSession();
await sandbox.writeFile('/workspace/session-file.txt', 'Session data', {
  sessionId: session.id
});

Error Handling

The method throws an error if:
  • The parent directory does not exist (use mkdir first)
  • The file cannot be written due to permissions
  • The path is invalid
  • Disk space is insufficient
try {
  await sandbox.writeFile('/nonexistent/file.txt', 'content');
} catch (error) {
  console.error('Failed to write file:', error.message);
  // Create directory first
  await sandbox.mkdir('/nonexistent', { recursive: true });
  await sandbox.writeFile('/nonexistent/file.txt', 'content');
}

Notes

  • If the file already exists, it will be overwritten
  • Parent directories must exist (use mkdir with recursive: true to create them)
  • File permissions are set to default (typically 644)

See Also

Build docs developers (and LLMs) love