File System Functions

Stone provides the file module for reading and writing files in your workspace.

file.read()

Read file contents. Requires importing the file module. Returns a record with the file text and detected format.

import file

Simple Read (Path String)

import file

content = file.read("data.json")

print(content.format)   // "json" (detected from extension)
print(content.text)     // Raw file contents

Read with Options Object

import file

content = file.read({
    path = "data.txt",
    format = "json"    // Override format detection
})

Read Options

path (string, required): the file path to read. format (string): override format detection ("json", "text", "csv"). encoding (string): file encoding (default "utf8").

Response Record

file.read() returns {text: string, format: string}. The format is auto-detected from extension: .json becomes "json", .csv becomes "csv", .xml becomes "xml", everything else becomes "text".

file.write()

Write content to a file. Returns a record indicating success.

Write String Content

import file

file.write("output.txt", "Hello, World!")

Write Object (Auto-Serialized)

import file

data = { name = "Alice", age = 30 }
file.write("user.json", data)

Write with Options Object

import file

file.write({
    path = "data.json",
    content = { items = [1, 2, 3] },
    pretty = true    // Pretty-print JSON (default: true)
})

Write Options

path (string, required): the file path to write. content (string or any, required): content to write, objects auto-serialize. pretty (bool): pretty-print JSON output (default true). encoding (string): file encoding (default "utf8").

Response Record

file.write() returns {success: bool, path: string}.

Using parse() with Files

Combine file.read() with the built-in parse() function for schema validation:

import file

User = { id: num, name: string, role: string = "user" }

content = file.read("user.json")
user = parse(content, User)

print(user.name)    // "Alice"
print(user.role)    // "user" (default if not in file)

Complete Example

import file

Config = {
    debug: bool = false,
    maxItems: num = 100,
    outputPath: string
}

content = file.read("config.json")
config = parse(content, Config)

results = processData(config.maxItems)
file.write(config.outputPath, results)

print("Done! Output written to: " + config.outputPath)

Error Handling

File operations throw on errors:

// File not found: "File not found: missing.txt"
// Permission denied: "Cannot read 'protected.txt': Permission denied"
// Write errors: "File write failed: ..."

Notes

Import file before calling file.read() or file.write(). The parse function is globally available without import. Paths are relative to your workspace root. Objects written to .json files are automatically serialized. File operations are asynchronous internally but appear synchronous to Stone code.