Filesystem Module

The fs module provides file I/O operations. Read and write files with simple function calls.

fs.readFile(path)

Reads a file and returns its contents as a string:

let content = fs.readFile("data.txt");
print(content);

Throws an error if the file cannot be read.

fs.writeFile(path, content)

Writes a string to a file:

fs.writeFile("output.txt", "Hello, World!");

// Write multiple lines
let data = "Line 1
Line 2
Line 3";
fs.writeFile("lines.txt", data);

Creates the file if it doesn't exist, overwrites if it does. Throws an error if the file cannot be written.

fs.append(path, content) — v0.1.5+

Appends a string to the end of a file (creates it if missing):

fs.append("log.txt", "new entry
");

fs.exists(path) — v0.1.5+

Returns true if the path exists, false otherwise:

if (fs.exists("config.txt")) {
    print("config found");
}

fs.listDir(path) — v0.1.5+

Returns an array of entry names in a directory:

let entries = fs.listDir("src");
for (name in entries) {
    print(name);
}

fs.setRoot(dir) — v0.1.5+ (sandbox)

Sets a sandbox root. Once set, every fs path is canonicalized and must resolve inside dir — attempts to escape (e.g., via ..) throw an error. Unset means unrestricted filesystem access (the default, for backwards compatibility).

fs.setRoot("data");
fs.readFile("data/config.txt");   // OK — inside the sandbox
fs.readFile("../secret.txt");     // error — escapes the root

Module name shadowing (v0.1.5+)

A variable named fs, math, or graph shadows the built-in module —fs.x then looks up field x on your variable. Use different names (e.g., filesys).

Example: Save and load config

class Config {
    fn save(filename, settings) {
        // Convert dict to simple format
        let content = "name=" + settings["name"] + "
";
        content = content + "value=" + settings["value"];
        fs.writeFile(filename, content);
    }
    
    fn load(filename) {
        return fs.readFile(filename);
    }
}

Error handling

Both functions throw runtime errors on failure (file not found, permission denied, etc.). Errors include the filename and line number for debugging.