KryonOSDocs
Storage & Security

Unified File System (FS)

Sandboxed LittleFS & MicroSD storage operations with on-demand permission prompts.

5. Unified File System (FS) & Scoped App Sandboxing

The FS global object controls the C++ virtual file system layer. It dynamically routes operations to the physical SD Card (prefixed with /sd/) or the high-speed Internal Flash (prefixed with /local/).

5.1 Scoped Application Sandboxing (v2.0.1+)

For security and privacy, all third-party JavaScript applications execute within a strictly sandboxed directory:

  • Sandbox Root: Applications are confined to their package folder (e.g. /local/apps/<app_name>/ or /sd/apps/<app_name>/).
  • Relative Path Resolution: Passing a relative filename (such as "data.json" or "levels/map1.dat") automatically resolves inside the app's sandboxed directory.
  • Protected Locations: Access to /system/, /local/system/, /sd/system/, or system vaults (wifi_credentials.enc, app_permissions.json) is forbidden and blocked at the Kernel level.
  • Path Traversal Protection: Any path containing .. or \ or attempting to escape the sandbox root is immediately rejected with null or false without interrupting the FreeRTOS watchdog.

FS.exists(path)

  • Parameters: path (String)
  • Returns: Boolean
  • Description: Validates if a file or folder physically exists within the application's sandbox. Returns false for out-of-sandbox or protected paths.

FS.readTextFile(path)

  • Parameters: path (String)
  • Returns: String (or null if the file doesn't exist)
  • Description: High-speed RAM loader. Reads the entire file into a contiguous String block in RAM. Do not use on files larger than ~20KB!

FS.writeTextFile(path, content)

  • Parameters: path (String), content (String)
  • Returns: Boolean
  • Description: Erases any existing file and writes the entirety of content to disk.

FS.appendTextFile(path, content)

  • Parameters: path (String), content (String)
  • Returns: Boolean
  • Description: Appends the given string to the end of an existing file.

FS.deleteFile(path)

  • Parameters: path (String)
  • Returns: Boolean
  • Description: Permanently deletes a file from the disk partition.

FS.renameFile(pathFrom, pathTo)

  • Parameters: pathFrom (String), pathTo (String)
  • Returns: Boolean
  • Description: Renames a file or moves it between directories on the same partition.

FS.listDir(path)

  • Parameters: path (String)
  • Returns: Array[String]
  • Description: Iterates through a directory and returns an array of absolute file paths (e.g. ["/local/app.js"]).

FS.mkdir(path)

  • Parameters: path (String)
  • Returns: Boolean
  • Description: Creates a new directory.

FS.rmdir(path, [recursive = false])

  • Parameters: path (String), recursive (Boolean, optional, default: false)
  • Returns: Boolean
  • Description: Removes a directory. When recursive is true, safely traverses subdirectories and deletes all enclosed files before removing the directory. Includes FreeRTOS Task Watchdog Timer yields, FAT32 . and .. filtering, two-phase directory snapshot traversal to protect LittleFS iterators, and recursion depth limit protection (depth <= 6). Root directories (/, /local, /sd) are strictly protected.

FS.isDirectory(path) / FS.isFile(path)

  • Parameters: path (String)
  • Returns: Boolean
  • Description: Evaluates if the target path is a directory or a file.

FS.getFileSize(path)

  • Parameters: path (String)
  • Returns: Integer (bytes)
  • Description: Returns the total physical size of a file in bytes.

FS.getTotalSpace(drive) / FS.getUsedSpace(drive) / FS.getFreeSpace(drive)

  • Parameters: drive (String - either "/local" or "/sd")
  • Returns: Integer (bytes)
  • Description: Returns exact storage metrics for the specified partition.

FS.getFileMD5(path)

  • Parameters: path (String)
  • Returns: String (Hex representation of MD5 hash)
  • Description: Leverages hardware-accelerated mbedtls cryptographic engine to stream the file and return its precise MD5 hash.

FS.mountSD() / FS.unmountSD()

  • Parameters: None
  • Returns: Boolean (mount returns success status)
  • Description: Triggers an SPI remount/unmount of the physical SD card.

FS.isSDMounted()

  • Parameters: None
  • Returns: Boolean
  • Description: Non-blocking hardware media guard returning true if a MicroSD card is mounted and responsive. Zero SPI bus overhead.

FS.copyFile(src, dst)

  • Parameters: src (String), dst (String)
  • Returns: Boolean
  • Description: Fast 4 KB buffered cross-partition stream copy (/sd ↔ /local). Features anti-self-copy protection, automated intermediate parent directory creation, ENOSPC disk-full rollback, and explicit FAT sector flushing.

FS.stat(path)

  • Parameters: path (String)
  • Returns: Object or null if the file/folder does not exist:
    {
        exists: true,        // Boolean
        isDirectory: false,  // Boolean
        isFile: true,        // Boolean
        size: 4096,          // File size in bytes (0 for directories)
        mtime: 1731000000,   // Unix timestamp (or 0 if unavailable)
        drive: "sd"          // "sd" or "local"
    }
    
  • Description: Consolidates multiple slow SPI bus round-trips into a single atomic native lookup. Includes LittleFS directory fallback for ESP32 Arduino core.

5.2 Chunked & High-Performance Binary File I/O (v3.0.0+)

FS.readChunk(path, offset, length, [asBinary = false])

  • Parameters: path (String), offset (Number), length (Number), asBinary (Boolean, optional, default: false)
  • Returns: String | Uint8Array | null
  • Description: Bypasses the ~20KB RAM ceiling by seeking and reading arbitrary byte ranges without loading the whole file into RAM. Clamped in C++ to a safe 16 KB allocation ceiling. Validates against negative numbers, NaN, or seek failures, returning null gracefully.

FS.readBinary(path)

  • Parameters: path (String)
  • Returns: Uint8Array | null
  • Description: Direct binary asset loading into a typed array (Uint8Array) for sprites, audio samples, and fonts. Returns an empty new Uint8Array(0) for 0-byte files. Bounded to 32 KB / free heap limit to prevent allocation panics; use FS.readChunk for larger streaming assets.

FS.writeBinary(path, buf)

  • Parameters: path (String), buf (Uint8Array | ArrayBuffer | String)
  • Returns: Boolean
  • Description: Writes raw binary buffers to disk. Correctly handles Uint8Array sub-views (e.g. buf.subarray(2, 5)). Features automated intermediate parent directory creation and ENOSPC rollback.

5.3 Native Modal File & Folder Pickers (v3.0.0+)

KryonOS provides a zero-heap modal UI file and folder browser that renders directly to the TFT glass without allocating arrays or objects on the Duktape JavaScript heap.

When invoked, the VM blocks synchronously in C++ while driving touch and display interactions. User selection in the picker automatically registers session authorization for the picked resource.

FS.pick(options) / FS.pickFile(options) / System.pickFile(options)

  • Parameters (options Object or Array):
    • title (String, default: "Select File"): Header title on the dialog.
    • startPath (String, default: "/local"): Initial directory to display.
    • extensions (Array<String>, default: []): File extension filters (e.g. [".bin", ".json", ".txt"]).
    • allowDrives (Boolean, default: true): Toggles access to /local vs /sd.
    • showHidden (Boolean, default: false): Toggles dotfiles visibility.
  • Shortcut: Passing an array directly acts as an extension shortcut: FS.pick([".bin", ".krai"]).
  • Returns: String | null (Absolute normalized path, or null if cancelled).
// Open file picker for AI binary models
var path = FS.pick({
    title: "Select AI Model",
    startPath: "/sd/models",
    extensions: [".bin", ".krai"],
    allowDrives: true
});

if (path) {
    console.log("User selected:", path);
    System.ai.load(path);
}

FS.pickDir(options) / FS.pickFolder(options) / System.pickDir(options)

  • Parameters (options Object):
    • title (String, default: "Select Folder"): Dialog title.
    • startPath (String, default: "/local"): Starting directory.
    • allowDrives (Boolean, default: true): Toggles drive switcher.
    • showCreate (Boolean, default: false): Enables inline + Dir folder creation button.
  • Returns: String | null (Absolute directory path, or null if cancelled).
var folder = FS.pickDir({
    title: "Select Save Directory",
    startPath: "/local",
    showCreate: true
});