Skip to main content

Description

Reads the contents of a file from the sandbox filesystem. Supports both text and binary files with automatic encoding detection.

Method Signature

async readFile(
  path: string,
  options?: { encoding?: string; sessionId?: string }
): Promise<ReadFileResult>

Parameters

path
string
required
Absolute path to the file to read
options
object
Optional configuration for the read operation
encoding
string
Encoding to use for reading 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

ReadFileResult
object
Result of the read operation
success
boolean
Whether the file was read successfully
path
string
Path to the file that was read
content
string
Content of the file (UTF-8 for text files, base64 for binary files)
timestamp
string
ISO 8601 timestamp of when the operation completed
encoding
'utf-8' | 'base64'
Encoding used for the content
isBinary
boolean
Whether the file is detected as binary
mimeType
string
MIME type of the file (e.g., ‘image/png’, ‘text/plain’)
size
number
File size in bytes
exitCode
number
Exit code from the underlying read command (0 = success)

Examples

Read a text file

const result = await sandbox.readFile('/workspace/hello.txt');
console.log(result.content); // File contents as string
console.log(result.mimeType); // 'text/plain'

Read a binary file

const result = await sandbox.readFile('/workspace/image.png');
if (result.isBinary) {
  // Content is base64-encoded
  const binaryData = atob(result.content);
  console.log(`Read ${result.size} bytes`);
}

Read with custom encoding

const result = await sandbox.readFile('/workspace/data.txt', {
  encoding: 'utf-8'
});
console.log(result.content);

Error Handling

The method throws an error if:
  • The file does not exist
  • The file cannot be read due to permissions
  • The path is invalid
try {
  const result = await sandbox.readFile('/workspace/nonexistent.txt');
} catch (error) {
  console.error('Failed to read file:', error.message);
}

See Also

Build docs developers (and LLMs) love