Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

File System

Perry implements Node.js file system APIs for reading, writing, and managing files.

Reading Files

const configPath = join(scratch, "config.json")
const content = readFileSync(configPath, "utf-8")
console.log(content)

Binary File Reading

const imagePath = join(scratch, "image.png")
const buffer = readFileBuffer(imagePath)
console.log(`Read ${buffer.length} bytes`)

readFileBuffer reads files as binary data (uses fs::read() internally, not read_to_string()).

Writing Files

const outputPath = join(scratch, "output.txt")
const dataPath = join(scratch, "data.json")
writeFileSync(outputPath, "Hello, World!")
writeFileSync(dataPath, JSON.stringify({ key: "value" }, null, 2))

File Information

if (existsSync(configPath)) {
    const stat = statSync(configPath)
    console.log(`Size: ${stat.size}`)
}

Directory Operations

// Create directory
const outDir = join(scratch, "output")
if (!existsSync(outDir)) mkdirSync(outDir)

// Read directory contents
const files = readdirSync(scratch)
for (const file of files) {
    console.log(file)
}

// Remove an empty directory
rmdirSync(outDir)

For recursive removal Perry exposes rmRecursive (a thin wrapper around std::fs::remove_dir_all). Wired via #193 through js_fs_rm_recursive in the LLVM backend.

import { rmRecursive } from "fs";
rmRecursive("output"); // Recursive remove; returns 1 on success, 0 on failure.

Path Utilities

const dir = dirname(configPath)
const cfgPath = join(dir, "config.json")
const name = basename(cfgPath)        // "config.json"
const abs = resolve("relative/path")  // Absolute path
console.log(`${name} ${abs.length > 0}`)

For import.meta.url → filesystem path conversion, use fileURLToPath from the url module:

import { fileURLToPath } from "url";
import { dirname } from "path";

const dir = dirname(fileURLToPath(import.meta.url));

Next Steps