Standard Library: Filesystem
File I/O is a set of global builtins, plus the fs object as an alias (fs.read / fs.write / fs.exists, …). There is no import std.fs.
Text and JSON files
writeFile("output.log", "startup\n");
const content = readFile("output.log");
writeJsonFile("settings.json", { env: "dev" });
const settings = readJsonFile("settings.json");
| Function | Description |
|---|---|
readFile(path) / fs.read | Read UTF-8 text |
writeFile(path, content) / fs.write | Replace the whole file |
readJsonFile / fs.readJson | Parse a JSON file |
writeJsonFile / fs.writeJson | Serialize JSON and replace the file |
createDirectory(path) / fs.createDirectory | Create a directory |
fileExists(path) / fs.exists | Existence check |
removePath(path) / fs.remove | Delete a file or directory |
listDirectory(path) / fs.list | Directory entries |
Writes replace the complete contents. Edit with an explicit read–modify–write cycle.
Streaming copy
copyFile(source, destination) copies bytes in 64KiB chunks and returns the byte count. It does not load the whole file into memory (Go io.Copy style).
createDirectory("scratch");
writeFile("scratch/source.txt", "streamed");
const copied = copyFile("scratch/source.txt", "scratch/dest.txt");
print(copied, readFile("scratch/dest.txt"));
Wrap filesystem work in try / catch. Errors carry code and message.