Skip to content

Files ​

serverside

Server scripts can read and write files in the server's data folder, the same tree the GRC File Browser shows. The global files object handles plain text, JSON and raw bytes, and can list, create, move, copy and delete files and folders.

Use files when the data is a document:

  • a config file staff edit by hand in the File Browser
  • a log you append to
  • content a script generates (levels, images, exported reports)
  • JSON you import or export in bulk
You need…Use
Config files, logs, generated content, import/exportfiles (this page)
Tables you query, sort, join or aggregateSQLite databases
Per-player or global records that clients mirror livereplicated collections
A handful of small key/value settingsflags

Paths ​

Paths are relative to the data folder and use forward slashes: 'config/shop.json', 'levels/arena.glvl'. A leading / is ignored. A path that climbs out of the data folder with .. is rejected, and so is any path that passes through a symbolic link.

Some folders belong to the engine and are protected:

PathScripts can…
accounts/, databases/, compile caches (compiledScripts/, compiledClientScripts/, compiledClassScripts/, ganiCompiled/, npcBuild/, npcCheck/)nothing. These are hidden from list() too. Use opendatabase for databases.
scripts/, flags.json, collections.jsonread, but not write
everything else (levels/, assets/, your own folders)read and write

Writing creates any missing parent folders, so you never need to mkdir before a write.

Reading and writing ​

Every call returns a Promise, so await it:

ts
// Text
await files.writeText('notes/todo.txt', 'buy swords\n')
const todo = await files.readText('notes/todo.txt')
await files.appendText('notes/todo.txt', 'sell shields\n')

// JSON
await files.writeJson('config/shop.json', { prices: { sword: 50 } })
const shop = await files.readJson<{ prices: Record<string, number> }>('config/shop.json')

// Bytes
const png = await files.readBytes('assets/images/logo.png')
await files.writeBytes('assets/images/logo-copy.png', png)
  • readText and writeText use UTF-8. A byte-order mark at the start of a file is dropped.
  • writeJson pretty-prints with 2 spaces. Pass a third argument to change that, or 0 for compact output. readJson rejects with EINVAL when the file isn't valid JSON.
  • writeText, writeJson and writeBytes replace a file atomically. Another reader sees either the old contents or the new ones, never half a file, even if the server stops mid-write. appendText adds to the end in place and creates the file if it's missing.

Folders and file management ​

ts
if (!(await files.exists('exports'))) await files.mkdir('exports')

for (const entry of await files.list('levels')) {
    if (!entry.isDirectory)
        echo(`${entry.path} - ${entry.size} bytes, modified ${new Date(entry.modified).toISOString()}`)
}

await files.copy('config/shop.json', 'backups/shop.json', { overwrite: true })
await files.rename('exports/old.csv', 'exports/archive/old.csv')
await files.delete('exports/archive', { recursive: true })
  • list(path?, { recursive? }) returns FileStat entries (name, path, isDirectory, size, modified) sorted by path. With no path it lists the data folder itself. stat(path) returns the same shape for one entry.
  • rename moves files and folders. copy handles files only. Both reject when the target exists unless you pass { overwrite: true }. rename never overwrites a folder.
  • delete removes a file or an empty folder. A folder with contents needs { recursive: true }.

Errors ​

A failed call rejects with a FileError: a normal Error with a code. Branch on the code, not the message:

CodeMeaning
ENOENTThe file or folder doesn't exist
EEXISTThe target exists and overwrite wasn't set
EACCESThe path is protected or read-only, or passes through a symbolic link
EISDIR / ENOTDIRFound a folder where a file was expected, or the reverse
ENOTEMPTYDeleting a folder with contents without recursive
EINVALA bad path or argument, or invalid JSON in readJson
EFBIGOver the size limits below
EIOAny other disk error
ts
async function loadOrDefault<T>(path: string, fallback: T): Promise<T> {
    try {
        return await files.readJson<T>(path)
    } catch (e) {
        if ((e as FileError).code === 'ENOENT') return fallback
        throw e
    }
}

Limits and behaviour ​

  • A single read or write can move up to 16 MB. Larger files reject with EFBIG, so rotate logs (for example one file per day) instead of growing one forever. list() returns at most 10,000 entries.
  • All file operations on the server run one at a time, in order, on a background worker. The game loop never waits on the disk, and a script's write followed by its read always sees the write.
  • Writing, copying or renaming a level file into a level folder hot-reloads it for players inside, exactly like saving it from GRC. New images and other assets are served as soon as they're written.
  • When a script hot-reloads, its pending file calls never resolve, just like its cancelled sleeps. The disk operation itself still completes.

Every server script shares this access

files is available to every server script, including NPC scripts in levels. Anyone who can edit scripts can read and change everything outside the protected folders.

Example: a config file and a join log ​

This script keeps its message of the day in config/motd.json, which staff can edit in the File Browser. It writes the defaults the first time it runs and re-reads the file once a minute. It also appends every login to a daily log file:

ts
// Server script: a message of the day kept in a JSON file that staff edit in
// the GRC File Browser (config/motd.json), plus a plain-text join log.

interface MotdConfig {
    enabled: boolean
    message: string
}

const CONFIG_PATH = 'config/motd.json'
const DEFAULTS: MotdConfig = { enabled: true, message: 'Welcome to the server!' }

let config: MotdConfig = DEFAULTS

async function loadConfig() {
    // First boot: write the defaults so staff have a file to edit.
    if (!(await files.exists(CONFIG_PATH))) {
        await files.writeJson(CONFIG_PATH, DEFAULTS)
        return
    }
    try {
        // Spread over the defaults so a file missing a key still works.
        config = { ...DEFAULTS, ...(await files.readJson<Partial<MotdConfig>>(CONFIG_PATH)) }
    } catch (e) {
        // A typo in the JSON shouldn't take the script down: keep the old config.
        const err = e as FileError
        echo(`[motd] ${CONFIG_PATH} not loaded (${err.code}): ${err.message}`)
    }
}

async function onInitialized() {
    await loadConfig()
    // Re-read once a minute so edits apply without reloading the script.
    setInterval(loadConfig, 60_000)
}

function onPlayerJoined(player: Player) {
    if (config.enabled)
        sendPM(player, config.message)

    // One log file per day, e.g. logs/joins-2026-10-09.log. Not awaited:
    // the join handler doesn't need to wait for the disk.
    const day = new Date().toISOString().slice(0, 10)
    files.appendText(`logs/joins-${day}.log`, `${new Date().toISOString()} ${player.account}\n`)
}