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
Absolute path where the file should be written
Content to write to the file
Optional configuration for the write operationEncoding to use for writing the file (e.g., ‘utf-8’, ‘base64’)
Session ID to use for this operation. If not provided, the default session is used.
Returns
Result of the write operationWhether the file was written successfully
Path to the file that was written
ISO 8601 timestamp of when the operation completed
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