Skip to content
Jennifer Programming Language

fs - filesystem I/O

Enable with use fs;. Blocking whole-file reads and writes, filesystem metadata, directory operations, and buffered file handles for line-oriented reads. Non-blocking use composes with spawn rather than duplicating each call as a *Async variant.

jennifer
use io;
use fs;

fs.writeString("hello.txt", "hi, world\n");
def content as string init fs.readString("hello.txt");
io.printf("%s", $content);

One-shot operations

Whole-file reads and writes.

CallReturnsNotes
fs.readString(path)stringWhole file as UTF-8. Invalid UTF-8 is an error with the byte offset; use fs.readBytes for binary files. A file over 256 MiB (32 MiB on jennifer-tiny) is an error; read it in chunks with the handle form.
fs.readBytes(path)bytesWhole file as raw bytes; same 256 MiB limit as readString. See below for the handle form.
fs.writeString(path, content)nullOverwrites. Creates the file if missing. See below for the handle form.
fs.writeBytes(path, content)nullOverwrites. Creates the file if missing. See below for the handle form.
fs.appendString(path, content)nullAppends. Creates the file if missing.
fs.writeNew(path, content)nullCreate path with content (a string or bytes), failing (catchable) if it already exists (O_EXCL; a symbolic link at path counts as existing and is not followed). If writing fails after the create (disk full, a file size limit), the file is removed again, so no truncated file is left behind. An atomic test-and-set: the primitive for a file-based advisory lock (the winner creates the file; every other creator errors). Unlike a symlink lock the result is a normal file, so fs.exists / fs.readString see it directly.
fs.appendBytes(path, content)nullAppends. Creates the file if missing.

Reading a file that doesn't exist is a positioned runtime error; use fs.exists(path) first when the "missing file is normal" case matters.

Metadata

Boundary-friendly predicates plus a full fs.stat.

CallReturnsNotes
fs.exists(path)boolTrue if the path resolves. Permission errors still surface.
fs.isFile(path)boolTrue iff the path exists and is a regular file. False for missing.
fs.isDir(path)boolTrue iff the path exists and is a directory. False for missing.
fs.stat(path)fs.StatMissing path errors. Pair with fs.exists when tolerating absent files.
fs.realpath(path)stringAbsolute, symlink-resolved canonical path. A missing / unresolvable path errors; a result that is not valid UTF-8 throws kind "fs".
fs.readlink(path)stringThe target a symlink points to, verbatim (the stored link text, not resolved; use fs.realpath to fully resolve). A non-symlink or missing path errors; a target that is not valid UTF-8 throws kind "fs".
fs.symlink(target, linkPath)nullCreate a symlink at linkPath pointing to target (argument order mirrors ln -s TARGET LINK). An already-existing linkPath errors; fs.remove it first to re-point.
fs.mkfifo(path[, mode])nullCreate a named pipe (FIFO) at path, owner-only 0o600 unless mode (in [0, 0o777], less the umask) says otherwise. An existing path errors. Unix only; elsewhere a catchable error.

fs.realpath follows every symlink in the chain and makes the result absolute, like the interpreter's own entry-script resolution for module imports. A tool installed by symlinking its entry point onto PATH gets the invocation path in os.ARGS[0] (the symlink), so to load data files that sit beside its real source rather than beside the symlink, resolve it:

jennifer
use os; use path; use fs;
def self as string init fs.realpath(os.ARGS[0]);   # the real file, symlinks followed
def assets as string init path.join(path.dir($self), "assets");

fs.mkfifo lets a child process stream into the program without a temporary file: the child writes the pipe while the program reads it with fs.open / fs.readLine. Opening either end blocks until the other end is opened too, so start the writer (os.spawn) before opening the read end.

jennifer
use fs; use os; use path;
def pipe as string init path.join(fs.makeTempDir(), "reads");
fs.mkfifo($pipe);
def p as os.Process init os.spawn(["sh", "-c", "gzip -dc reads.fq.gz > " + $pipe]);
def f as fs.File init fs.open($pipe, "read");

fs.Stat

text
def struct fs.Stat {
    path as string,        # the path as passed to fs.stat / fs.walk
    size as int,           # bytes; -1 for directories
    isDir as bool,
    mtimeNanos as int,     # Unix nanoseconds
    mode as int            # POSIX permission bits (e.g. 0o644, 0o755)
};

fs.StatBytes (from fs.walkBytes) has the same fields with path as bytes.

mtimeNanos is an int, not a time.Time, which keeps fs independent of the time library. Converting is one line:

jennifer
use fs;
use io;
use time;

def stat as fs.Stat init fs.stat("hello.txt");
def modified as time.Time init time.fromUnixNanos($stat.mtimeNanos);
io.printf("modified: %s\n", time.iso($modified));

size is -1 for directories so it can't be mistaken for "empty directory."

Permissions

The write verbs create files at a fixed 0644; fs.chmod tightens (or loosens) a file after the fact, e.g. to 0600 for a secret / token store that must not be world-readable. fs.chown sets owner and group.

CallReturnsNotes
fs.chmod(path, mode)nullSets the permission bits; mode is the low 12 bits (e.g. 0o600, 0o755), rejected outside [0, 0o7777]. The setuid / setgid / sticky bits (0o4000 / 0o2000 / 0o1000) are applied, and fs.stat(...).mode reports them back.
fs.chown(path, uid, gid)nullSets owner / group; -1 leaves that id unchanged. An id outside -1..4294967295 (2147483647 on 32-bit builds) is an error. Usually needs privilege.
jennifer
use fs;
fs.writeString("token.json", $tokenJson);
fs.chmod("token.json", 0o600);   # owner-only, like a gh / aws token store

Both are Linux/Unix semantics and match the platform target. On Windows fs.chmod honours only the read-only bit and fs.chown always fails; the error is catchable like any other fs failure.

Reading a secret

A key, token or password file is read with fs.readSecretBytes, which refuses a file others could have read or replaced, the way OpenSSH refuses a private key with loose permissions.

CallReturnsNotes
fs.readSecretBytes(path)bytesThe whole file, once it passes the checks below.
fs.readSecretString(path)stringThe same, as UTF-8 text (invalid UTF-8 is an error).

The checks run on the opened file, not on the path, so the file read is the file checked. Each refusal is kind "fs", with a message naming the path. Anything but a regular file once symbolic links are followed (a directory, a FIFO, a device) is refused; a FIFO without waiting for a writer. The rest depends on where the file lives:

The file is onRefused when
a writable filesystemany group or other permission bit (mode & 0o077; the message gives the mode and the fix, run chmod 600 PATH), or an owner other than the effective user or root
a read-only mountgroup or others could write it (mode & 0o022)

A read-only mount is how container runtimes hand secrets in: Docker and Compose /run/secrets, Kubernetes secret volumes. Nothing in the container can replace such a file, and whoever made the mount chose who reads it, so a Swarm secret (0444, owned by root), a Kubernetes one (0644) or a Compose file owned by the host user all read. The mount is asked of the open file (fstatfs), on Linux; elsewhere every file gets the writable-filesystem check.

A file over 1 MiB is kind "limit"; a secret is small. A missing or unreadable file is the same error as for fs.readBytes. On a platform without POSIX permission bits every call is refused (kind "fs") rather than read unchecked.

jennifer
use fs;
use os;

# JWT_KEY_FILE names a file written with fs.chmod(path, 0o600) or chmod 600
def key as bytes init fs.readSecretBytes(os.getEnv("JWT_KEY_FILE"));

Directory operations

Create and delete have two verbs each (mkdir / mkdirAll, remove / removeAll). The safe non-recursive form keeps the short name; the recursive form gets an explicit second name so a code review can grep for the risky sites (a bool parameter or mode string would hide the recursive intent at the call site).

CallReturnsNotes
fs.mkdir(path)nullErrors if any parent is missing (matches POSIX mkdir).
fs.mkdirAll(path)nullCreates every missing parent (matches POSIX mkdir -p).
fs.remove(path)nullRemoves one file or one empty directory. Non-empty dir errors.
fs.removeAll(path)nullRecursive delete. Explicit second verb.
fs.rename(old, new)nullSame-filesystem rename; cross-fs is a boundary error. An existing file at new is replaced, atomically on Linux / macOS (POSIX rename(2)): the write-temp-then-rename way to save a config or certificate with no window where the file is missing. Replacing a directory errors.
fs.syncDir(path)nullFlush the directory's entries to the storage device (open read-only, fsync), so a file created, renamed or removed in it survives a crash. A path that is not a directory errors. A no-op on Windows (no directory flush). See Durable replace.
fs.list(path)list of stringSorted entry names. Non-recursive. A name that is not valid UTF-8 throws kind "fs".
fs.listBytes(path)list of bytesfs.list with each name as bytes, whatever the filesystem holds.
fs.walk(path)list of fs.StatDepth-first, sorted, includes path itself as the first entry. Skips symlinks below the root (a symlinked root is followed). An unreadable directory below the root is listed but not descended into; an unreadable root is an error. A path that is not valid UTF-8 throws kind "fs".
fs.walkBytes(path)list of fs.StatBytesfs.walk with each path as bytes: fs.StatBytes is fs.Stat with path as bytes.

Linux filesystems store any byte but / and NUL in a name. list, walk, readlink and realpath return names as string, so they refuse one that is not valid UTF-8 (fs.list: /srv/in: entry "a\xffb" is not valid UTF-8 at byte 1; fs.listBytes returns names as bytes); a program that must handle any name uses listBytes / walkBytes.

jennifer
use fs;

# Safe: mkdir refuses to create with missing parents.
fs.mkdirAll("build/output/cache");        # explicit intent

# Safe: remove refuses to delete non-empty directories.
fs.removeAll("build/output/cache");       # explicit intent

Temporary files and directories

fs.makeTempFile and fs.makeTempDir create a fresh, uniquely-named entry and return its path (not an open handle), for use with the ordinary path-based verbs. Creation is atomic (the OS reserves the name, so two concurrent callers never collide) and restrictive (0600 for a file, 0700 for a directory), so scratch data holding secrets is not world-readable.

CallReturnsNotes
fs.makeTempFile([dir[, prefix[, suffix]]])stringCreate an empty unique file; returns its path.
fs.makeTempDir([dir[, prefix]])stringCreate a unique directory; returns its path.

Arguments are positional and trailing-optional, "" meaning the default:

ArgumentMeaning
dirWhere to create it. "" (or omitted) uses the system temp directory (os.tempDir(): $TMPDIR, else /tmp on Linux). An explicit dir must already exist: only the final unique component is created (like fs.mkdir, not fs.mkdirAll).
prefix / suffixName the entry around the random component; suffix gives a file a real extension. A path separator or NUL in either (it would escape the target directory) is a positioned error.
jennifer
use fs;

# A scratch file in the system temp dir, cleaned up when done.
def report as string init fs.makeTempFile("", "report-", ".json");
defer fs.remove($report);              # cleanup runs however the block exits
fs.writeString($report, $payload);
# ... use it ...

# A scratch directory under an existing build tree (create the parent first).
fs.mkdirAll("build");
def work as string init fs.makeTempDir("build", "job-");
defer fs.removeAll($work);
# ... write files under $work ...

Both are strict: any OS failure (a read-only filesystem, no permission, a missing parent directory, or a name the filesystem cannot hold) is a catchable error, never a fabricated directory tree or a name mangled to fit. Nothing is cleaned up automatically: pair every makeTemp* with an fs.remove / fs.removeAll, ideally as a defer right after the create (as above) so the cleanup also runs when an error unwinds through the block (control-flow > defer; see the concurrency and error notes below).

File handles

For line-oriented reads and files that don't fit comfortably in memory, fs.open returns an fs.File handle backed by the integer-registry pattern also used by hash.Stream and crc.Stream.

text
def struct fs.File { id as int };

Mode strings use the codec-table shape:

ModeSemantics
"read"Read-only. fs.readLine, fs.readChars, fs.readBytes allowed.
"write"Write, create+truncate. fs.writeString, fs.writeBytes allowed.
"append"Write, create+append. Same write ops as "write".

Unknown mode strings error with the known set listed.

Handle surface

CallReturnsNotes
fs.open(path, mode)fs.FileOpens per the mode string.
fs.close($f)nullRemoves the handle from the registry; later ops on the id throw kind "closed". A second close does nothing.
fs.readLine($f)stringOne line; \r\n / \n stripped. Errors on EOF; check fs.eof first. A line over 256 MiB (32 MiB on jennifer-tiny) is an error. An invalid UTF-8 line is consumed and is an error with the offset in the line; use fs.readBytes($f, n) for binary data.
fs.readChars($f, n)stringUp to n runes, UTF-8 decoded. Partial result on EOF, sticky-EOF flip. n above 64 Mi (8 Mi on jennifer-tiny) is an error. An invalid byte is an error with its offset in this call's read (bytes before it consumed); use fs.readBytes($f, n) for binary data.
fs.readBytes($f, n)bytesUp to n bytes, n <= 256 MiB (32 MiB on jennifer-tiny); the buffer grows with the data read. Partial result on EOF, sticky-EOF flip.
fs.writeString($f, s)nullRead-mode handle errors.
fs.writeBytes($f, b)nullRead-mode handle errors.
fs.sync($f)nullFlush written data to the storage device (fsync); handle stays open. Read-mode handle errors.
fs.eof($f)boolLooks ahead: true iff the next read would error / return partial.
fs.seek($f, offset)nullMove to offset bytes from the start. Negative offset errors. Read handle: the read buffer and EOF flag are dropped; past the end the next read is end of input. Write handle: the next write goes at offset (a gap past the end reads as zero bytes). Append handle errors (writes always go to the end). A handle that cannot seek (FIFO, terminal) errors.
fs.tell($f)intCurrent position in bytes from the start: after a readLine the start of the next line, not the OS offset of the read buffer. Append handle: the end of the file. A handle that cannot seek errors.

The canonical read-loop:

jennifer
use io;
use fs;

def f as fs.File init fs.open("input.txt", "read");
while (not fs.eof($f)) {
    def line as string init fs.readLine($f);
    io.printf("[%s]\n", $line);
}
fs.close($f);

fs.readLine on a handle whose next read is EOF errors with end of input, hence the fs.eof($f) guard. fs.eof looks one byte ahead (through the buffered reader) so a file ending cleanly with \n still trips the guard after the last line comes out.

Durability: sync vs close. fs.close guarantees the bytes reach the operating system, not the disk: the OS may still hold them in its cache after close returns. fs.sync($f) forces the file's written data all the way to the storage device (an fsync) and leaves the handle open. This is the "safe to remove the USB stick" step: sync explicitly so a failure surfaces before you tell the user it is safe:

jennifer
use fs;
use io;

def f as fs.File init fs.open("/media/usb/report.csv", "write");
fs.writeString($f, $payload);
fs.sync($f);                           # push it to the device; errors if the write failed
io.printf("safe to remove the stick\n");
fs.close($f);

fs.sync requires a write- or append-mode handle (a read handle has nothing to flush). fsync covers the OS side; a removable device's own internal cache is the job of the OS eject / unmount.

Durable replace

fs.sync makes a file's data durable, not its name: the name lives in the directory. A write-temp-then-rename save survives a crash once the temp file is synced before the rename and the directory after it:

jennifer
use fs;

def f as fs.File init fs.open("data/state.json.tmp", "write");
fs.writeString($f, $json);
fs.sync($f);                               # the data
fs.close($f);
fs.rename("data/state.json.tmp", "data/state.json");
fs.syncDir("data");                        # the new name

On Linux and macOS fs.syncDir opens the directory read-only and fsyncs it. On Windows, which has no flush for a directory, it only checks that path is a directory.

Reading at an offset

fs.seek jumps to a byte offset without reading what comes before it, so a reader that resumes from a saved position costs the same at any offset:

jennifer
use fs;

def f as fs.File init fs.open("data.log", "read");
fs.seek($f, 1048576);                  # 1 MiB in
def chunk as bytes init fs.readBytes($f, 4096);
def next as int init fs.tell($f);      # where to resume
fs.close($f);

The offset counts bytes; seeking into the middle of a UTF-8 sequence makes the next fs.readLine / fs.readChars throw kind "fs".

Polymorphic verbs (path vs handle)

Three verbs are polymorphic on the first argument's kind:

Verb1-arg form2-arg form
fs.readBytes(path) -> whole($f, n) -> partial handle read
fs.writeString-(path, content) or ($f, s)
fs.writeBytes-(path, content) or ($f, b)

The dispatcher picks based on whether the first argument is a string (path form) or an fs.File (handle form). Any other kind is a positioned boundary error.

Handles share state between copies

An fs.File{id} value is small; copies share the underlying Go *os.File state via the integer id, an exception to value semantics like task of T:

jennifer
def a as fs.File init fs.open("x.txt", "read");
def b as fs.File init $a;              # `b` and `a` reference the same file
fs.close($a);                          # closes for both
def s as string init fs.readLine($b);  # throws kind "closed": id is not open

Watching for changes

fs.watch starts a background watch over a file or directory and returns an fs.Watcher handle; a pull loop drains change events (the same shape as an httpd server), so a spawned loop reacts to changes while the program does other work (a dev server rebuilding on save, a live reloader).

CallReturnsNotes
fs.watch(path)fs.WatcherWatch a file, or a directory recursively. Default poll ~300 ms.
fs.watchWith(path, fs.WatchOptions)fs.WatcherSame, polling every WatchOptions.intervalMs: 0 is the ~300 ms default, otherwise at least 20 and small enough to fit a duration (a smaller, negative or larger value is a catchable error).
fs.next($w)fs.EventBlock until the next change; throws kind "closed" if the watcher is closed (which is how a blocked loop is released).
fs.hasEvent($w)boolWhether an event is queued (non-blocking peek).
fs.close($w)nullStop the watcher. fs.close is polymorphic over fs.File and fs.Watcher.

At most 1024 watchers are open at once; one more is kind "limit".

An fs.Event is { path as string, kind as string, isDir as bool }, where kind is "created", "modified", or "deleted".

jennifer
use fs; use io;
def w as fs.Watcher init fs.watchWith("content", fs.WatchOptions{intervalMs: 200});
def worker as task of null init spawn {
    try {
        while (true) {
            def e as fs.Event init fs.next($w);   # blocks until something changes
            if (not $e.isDir) {                    # ignore bare directory-mtime bumps
                io.printf("rebuild: %s %s\n", $e.kind, $e.path);
            }
        }
    } catch (stop) {
        # fs.next errors when fs.close releases the watcher: a clean shutdown.
    }
};
# ... serve here; `fs.close($w)` ends the loop, then `task.wait($worker)`.

How it works, and the trade-offs. The watch is mtime polling (a background goroutine re-scans the tree each interval and diffs a snapshot), not inotify, so it works on both binaries, matching jennifer serve --watch. Two consequences:

  • Bursts coalesce. An editor's save (write / rename / chmod) within one poll interval collapses into one event per path: a save is one "modified", not three. Very short-lived transients (a file created and deleted between two polls) may not be reported; the watch reflects the net change.
  • Directory mtimes fire. Adding or removing a file bumps its directory's mtime, so you get a "modified" event for the directory alongside the child's "created" / "deleted". Filter with $e.isDir when you only care about files.

For a huge tree (100k+ files) polling gets expensive; the target is dev tooling watching hundreds to low thousands of files.

Concurrency composition

fs is blocking. Non-blocking use is a one-line composition with spawn:

jennifer
use fs;
use task;

def t as task of string init spawn {
    return fs.readString("/etc/hosts");
};
def content as string init task.wait($t);

Multiple files in parallel:

jennifer
use fs;
use task;

func loadOne(path as string) {
    return fs.readString($path);
}

def paths as list of string init ["a.txt", "b.txt", "c.txt"];
def tasks as list of task of string init [];
for (def p in $paths) {
    $tasks[] = spawn { return loadOne($p); };
}
def contents as list of string init task.waitAll($tasks);

Under the default jennifer binary this parallelises across cores; under jennifer-tiny (TinyGo, cooperative single-threaded scheduler) the composition is correct but sequential. See ../technical/tinygo.md.

Errors and messages

Errors

KindRaised for
"fs"text that is not valid UTF-8 in readString, readLine, readChars and readSecretString, and a name that is not in list, walk, readlink and realpath; a secret file refused by readSecretBytes / readSecretString (Reading a secret)
"limit"a size cap, the open-handle or watcher count
"closed"any call but close on a closed fs.File or fs.Watcher, and an fs.next the watcher's close wakes
"runtime"an operating-system failure (a missing file, a permission denied, ...) and misuse: a wrong argument, an unknown mode, a handle used in the wrong mode

Messages

Every error is positioned at the Jennifer call site with the path or handle id in the message. An operating-system failure reads fs.FUNC: PATH: CAUSE (fs.rename and fs.symlink: fs.FUNC: PATH -> PATH: CAUSE), naming each path once.

CauseExample message
Missing file (fs.readString / fs.readBytes / fs.stat)fs.readString: PATH: no such file or directory
Non-empty directory given to fs.remove (use fs.removeAll)fs.remove: PATH: directory not empty
Missing parent given to fs.mkdir (use fs.mkdirAll)fs.mkdir: PATH: no such file or directory
Wrong mode for the operation (same shape in reverse for a read handle given a write)fs.readLine: fs.File "x.txt" was opened in mode "write"; open with mode "read" to read
Unknown mode stringfs.open: unknown mode "rw"; known: "read", "write", "append"
Use after close, kind "closed"fs.readLine: fs.File id 3 is not open (already closed, or never opened)
Negative countfs.readChars: n must be non-negative, got -1
Size limits, kind "limit" (as is reaching the open-handle or watcher count)fs.readBytes: PATH exceeds the 268435456-byte limit; read it in chunks with fs.open and fs.readBytes($f, n) (also readString), fs.readLine: PATH: line exceeds the 268435456-byte limit, fs.readChars: N exceeds the 67108864-character per-call limit
Secrets, kind "fs" (see Reading a secret)fs.readSecretBytes: PATH has group or other permissions (mode 0644); run chmod 600 PATH
Invalid UTF-8 in a text read, kind "fs" (also fs.readLine, fs.readChars and fs.readSecretString; the offset is within the returned text; the bytes reads accept any content)fs.readString: PATH: invalid UTF-8 at byte 5
A name that is not UTF-8, kind "fs" (the offset is within the name; walk names the whole path)fs.list: PATH: entry "a\xffb" is not valid UTF-8 at byte 1; fs.listBytes returns names as bytes, fs.readlink: PATH: link target "t\xff" is not valid UTF-8 at byte 1

Every error is catchable with try / catch:

jennifer
use fs;
use io;

try {
    def s as string init fs.readString("optional-config.toml");
} catch (e) {
    io.printf("no config, using defaults: %s\n", $e.message);
}

Deprecated

Each still works and is removed in 0.29.0; jennifer lint reports a call (L301).

DeprecatedUse instead
fs.watch(path, intervalMs)fs.watchWith(path, fs.WatchOptions{intervalMs: ...})

What's left out

Not providedInstead
Streaming line iterator (for (def line in fs.lines(path)))fs.open + while (not fs.eof($f)).
fs.copy(src, dst)Read and write the bytes, then fs.chmod if the mode matters.
fs.stat($f) on an open handleThe path-based fs.stat.
Event-driven watch (inotify / kqueue / FSEvents)fs.watch polls modification times, which keeps it working on both binaries.
Following symlinks in fs.walkNot done, to avoid symlink loops; resolve a link with fs.realpath and walk that.

See also

  • ../user-guide/concurrency.md - the spawn-and-compose story fs builds on.
  • task - observe handles produced by spawn.
  • time - time.fromUnixNanos converts fs.Stat.mtimeNanos into a time.Time.
  • os - process-level operations that pair with fs: env vars, argv, external commands.

Academy talks

TalkWhat it shows
Jennifer 0.27: what's new, what's deprecated, what breaksreading secret files with permission checks
Your first command-line toolrenaming files with existence checks and a dry run
Your own small blog with Jenniferreading posts and writing the generated site to disk