Skip to content

std::fs

Files and directories. Every function takes a path as a String (std::path works on them) and returns a Result whose error is io.Error, which names the path it is about: NotFound, AlreadyExists, IsADirectory and the rest. An empty path or one holding a NUL byte is InvalidPath, and every error names the path as the program passed it. A relative path is resolved against the working directory, fs.current_dir(), which a program cannot change. Reads, writes, metadata and exists follow symlinks; a path through more than 40 is Other with code ELOOP.

The functions reach the file system the running call is given. A native program run by nomi run or built by nomi build, and a wasip1/wasm module, reach the operating system’s (under WASI, the directories the runner opens for it). A js/wasm module reaches one in memory, whose working directory is /work: empty under Go’s Node loader, and seeded by run’s files option in the browser (Building). Inside std::fs::testing.run a call reaches a sandbox in memory, so a test checks what a function reads and writes without touching the disk. Tasks reach the file system of the frame they were started on.

import
    std::fs
    std::io
end

fn main() -> Result<Unit, io.Error>
    fs.write_text("notes.txt", "milk\n")?
    fs.write_text("notes.txt", "eggs\n", mode: .Append)?
    io.print(fs.read_text("notes.txt")?)
    Ok(Unit)
end

Import with import std::fs.

enum WriteMode
    Replace
    ReplaceAtomically
    Append
    New
end

How a write treats what is already at its path.

Variants

  • Replace

    Create the file, or empty it when it exists, and write from the start.

  • ReplaceAtomically

    Write a temporary file beside the path and rename it over the path when the write ends, so a reader sees the old contents or the new, never part of either. A write that fails leaves the old file as it was.

  • Append

    Create the file when it is missing, and write at its end.

  • New

    Fail with AlreadyExists when something is at the path.

import std::fs::testing.{self, Sandbox}

ran = testing.run(Sandbox{files: {"log.txt" => "a\n"}}, fn ->
    _ = write_text("log.txt", "b\n", mode: WriteMode.Append)
    write_text("log.txt", "c\n", mode: WriteMode.New)
end)

assert ran.value == Err(Error.AlreadyExists{path: "log.txt"})
assert testing.text(ran, "/work/log.txt") == Some("a\nb\n")

impl Debug for WriteMode

fn inspect(value: WriteMode) -> String

impl Debug.inspect

impl Equatable for WriteMode

fn equal(a: WriteMode, b: WriteMode) -> Bool

impl Equatable.equal

enum Kind
    File
    Directory
    Symlink
    Other
end

What a path names.

Variants

  • Other

    A device, a socket, a pipe: something that is none of the others.

impl Debug for Kind

fn inspect(value: Kind) -> String

impl Debug.inspect

impl Equatable for Kind

fn equal(a: Kind, b: Kind) -> Bool

impl Equatable.equal

struct Entry
    path: String
    name: String
    kind: Kind
end

One entry of a directory, from fs.list.

impl Debug for Entry

fn inspect(value: Entry) -> String

impl Debug.inspect

impl Equatable for Entry

fn equal(a: Entry, b: Entry) -> Bool

impl Equatable.equal

struct Metadata
    kind: Kind
    size: Int
    modified: Instant
    mode: Int
end

What fs.metadata returns about a path.

impl Debug for Metadata

fn inspect(value: Metadata) -> String

impl Debug.inspect

impl Equatable for Metadata

fn equal(a: Metadata, b: Metadata) -> Bool

impl Equatable.equal

fn read(path: String) -> Result<Bytes, Error>

The whole file at path, as bytes.

data = fs.read("photo.png")?
import std::fs::testing.{self, Sandbox}

ran = testing.run(Sandbox{binary: {"b.bin" => String.to_bytes("ab")}}, fn -> read("b.bin"))
assert ran.value == Ok(String.to_bytes("ab"))
fn read_text(path: String) -> Result<String, Error>

The whole file at path, as text. Bytes that are not UTF-8 are InvalidText, with the offset of the first bad one. Nothing at the path is NotFound, which a program that makes its data file on first run treats as empty. A directory is IsADirectory.

case fs.read_text("notes.txt")
    Ok(text)                        -> io.print(text)
    Err(io.Error.NotFound{path: _}) -> io.print("no notes yet")
    Err(e)                          -> io.eprint("cannot read the notes: ${e}")
end
import std::fs::testing.{self, Sandbox}

ran = testing.run(Sandbox{files: {"notes.txt" => "milk"}}, fn ->
    [read_text("notes.txt"), read_text("todo.txt")]
end)

assert ran.value == [Ok("milk"), Err(Error.NotFound{path: "todo.txt"})]
fn write(path: String, data: Bytes, mode: WriteMode = WriteMode.Replace) -> Result<Unit, Error>

Writes data to path. By default it replaces the file; mode says otherwise (WriteMode). The directory must exist: a missing one is NotFound naming the directory. A new file’s permissions are 0o644, and an atomic write keeps the old file’s.

fs.write("out.bin", data)?
import std::fs::testing.{self, Sandbox}

ran = testing.run(Sandbox{}, fn ->
    [write("a.bin", String.to_bytes("a")), write("missing/b.bin", String.to_bytes("b"))]
end)

assert ran.value == [Ok(Unit), Err(Error.NotFound{path: "missing"})]
assert ran.files == {"/work/a.bin" => String.to_bytes("a")}
fn write_text(path: String, text: String, mode: WriteMode = WriteMode.Replace) -> Result<Unit, Error>

Writes text to path as UTF-8, as fs.write writes bytes.

fs.write_text("log.txt", "started\n", mode: .Append)?
import std::fs::testing.{self, Sandbox}

ran = testing.run(Sandbox{files: {"out.txt" => "old"}}, fn ->
    write_text("out.txt", "new", mode: WriteMode.ReplaceAtomically)
end)

assert ran.value == Ok(Unit)
assert testing.text(ran, "/work/out.txt") == Some("new")
fn lines(path: String) -> Iter<Result<String, Error>>

Each line of the file at path, as Reader.lines reads them: without its \n and a \r before it, and with a last line that has no newline. Each run of the iterator opens the file, reads it and closes it, so it can run more than once, and a consumer that stops early closes the file when it stops. A failure (the file is missing, a line is not UTF-8) is the last item.

names = Result.collect(fs.lines("names.txt"))?
import std::fs::testing.{self, Sandbox}

ran = testing.run(Sandbox{files: {"in.txt" => "pear\r\napple"}}, fn ->
    each = lines("in.txt")
    (Result.collect(each), Iter.first(each), Result.collect(lines("none.txt")))
end)

assert ran.value == (
    Ok(["pear", "apple"]),
    Some(Ok("pear")),
    Err(Error.NotFound{path: "none.txt"}),
)

assert ran.open == []
fn chunks(path: String, size: PositiveInt = 65536) -> Iter<Result<Bytes, Error>>

The file at path in pieces of at most size bytes, as fs.lines reads it: each run opens the file again.

pieces = fs.chunks("big.bin", size: 4096) |> Iter.count()
import std::fs::testing.{self, Sandbox}

ran = testing.run(Sandbox{files: {"a.txt" => "abcde"}}, fn ->
    chunks("a.txt", size: 2) |> Result.collect()
end)

assert ran.value == Ok([String.to_bytes("ab"), String.to_bytes("cd"), String.to_bytes("e")])
fn open(path: String) -> Result<Reader, Error>

A reader over the file at path. Defer Reader.close_quietly on the next line, so the file is closed however the function ends.

r = fs.open("notes.txt")?

defer Reader.close_quietly(r)
import std::fs::testing.{self, Sandbox}

fn first_line(path: String) -> Result<Maybe<String>, Error>
    r = open(path)?
    defer Reader.close_quietly(r)
    Reader.read_line(r)
end

ran = testing.run(Sandbox{files: {"a.txt" => "one\ntwo\n"}}, fn -> first_line("a.txt"))

assert ran.value == Ok(Some("one"))
assert ran.open == []
fn create(path: String, mode: WriteMode = WriteMode.Replace) -> Result<Writer, Error>

A writer over the file at path, which mode treats as fs.write does. What is written is buffered until Writer.flush or Writer.close.

Defer Writer.discard on the next line, and end the success path with Writer.close(w)?, which commits the write and reports a failed close. When the function leaves any other way, an Err or a trap, the deferred discard gives the writer up. With ReplaceAtomically it drops the temporary file, and the old file is left as it was. With any other mode it closes the file, which keeps what was written to it. A discard after the close does nothing.

fn save(path: String, rows: List<String>) -> Result<Unit, io.Error>
    w = fs.create(path, mode: .ReplaceAtomically)?
    defer Writer.discard(w)

    Writer.write_lines(w, rows)?
    Writer.close(w)?
    Ok(Unit)
end
import std::fs::testing.{self, Sandbox}

fn save(path: String, rows: List<String>, fail: Bool) -> Result<Unit, Error>
    w = create(path, mode: WriteMode.ReplaceAtomically)?
    defer Writer.discard(w)
    Writer.write_lines(w, rows)?
    if fail then return Err(Error.TimedOut)
    Writer.close(w)?
    Ok(Unit)
end

saved = testing.run(Sandbox{files: {"out.txt" => "old\n"}}, fn ->
    save("out.txt", ["new"], False)
end)

assert saved.value == Ok(Unit)
assert testing.text(saved, "/work/out.txt") == Some("new\n")

failed = testing.run(Sandbox{files: {"out.txt" => "old\n"}}, fn ->
    save("out.txt", ["new"], True)
end)

assert failed.value == Err(Error.TimedOut)
assert testing.text(failed, "/work/out.txt") == Some("old\n")
assert failed.open == []

appended = testing.run(Sandbox{files: {"log.txt" => "a\n"}}, fn ->
    w = create("log.txt", mode: WriteMode.Append)?
    defer Writer.discard(w)
    _ = Writer.write_text(w, "b\n")
    Writer.discard(w)
    Writer.close(w)
end)

assert appended.value == Err(Error.Closed)
assert testing.text(appended, "/work/log.txt") == Some("a\nb\n")
assert appended.open == []
enum Access
    Read
    ReadWrite
    Create
end

How fs.open_file opens a file.

Variants

  • Read

    Reads only; a write is PermissionDenied. The file must exist.

  • ReadWrite

    Reads and writes. The file must exist.

  • Create

    Reads and writes, making the file, empty, when it is missing. An existing file keeps its contents.

impl Debug for Access

fn inspect(value: Access) -> String

impl Debug.inspect

impl Equatable for Access

fn equal(a: Access, b: Access) -> Bool

impl Equatable.equal

fn open_file(path: String, access: Access = Access.Read) -> Result<File, Error>

A File on path for reads and writes at a position (io.File): File.read_at, File.write_at, File.seek. A write reaches the file as it is made, so there is nothing to give up: defer File.close_quietly on the next line, and end the success path with File.close(f)? when a failed close should be reported.

fn patch_header(db: String, header: Bytes) -> Result<Unit, io.Error>
    f = fs.open_file(db, access: .ReadWrite)?
    defer File.close_quietly(f)

    File.write_at(f, 0, header)?
    File.close(f)
end
import std::fs::testing.{self, Sandbox}

ran = testing.run(Sandbox{}, fn ->
    [
        Result.map(open_file("none.bin"), fn _ -> Unit),
        Result.map(open_file(".", access: Access.Create), fn _ -> Unit),
    ]
end)

assert ran.value == [Err(Error.NotFound{path: "none.bin"}), Err(Error.IsADirectory{path: "."})]

edited = testing.run(Sandbox{files: {"a.txt" => "abcdef"}}, fn ->
    f = open_file("a.txt", access: Access.ReadWrite)?
    defer File.close_quietly(f)
    head = File.read(f, max: 2)?
    tail = File.read_at(f, 4, max: 8)?
    File.write(f, String.to_bytes("XY"))?
    File.write_at(f, 8, String.to_bytes("!"))?
    at = File.position(f)?
    size = File.size(f)?
    File.seek(f, 0)?
    whole = File.read(f)?
    File.truncate(f, 3)?
    Ok((head, tail, at, size, whole))
end)

assert edited.value == Ok(
    (
        Some(String.to_bytes("ab")),
        Some(String.to_bytes("ef")),
        4,
        9,
        Some(String.to_bytes("abXYef\u{0}\u{0}!")),
    )
)

assert testing.text(edited, "/work/a.txt") == Some("abX")
assert edited.open == []

read_only = testing.run(Sandbox{files: {"a.txt" => "a"}}, fn ->
    f = open_file("a.txt")?
    defer File.close_quietly(f)
    File.write(f, String.to_bytes("b"))
end)

assert read_only.value == Err(Error.PermissionDenied{path: "a.txt"})
assert read_only.open == []

patched = testing.run(Sandbox{files: {"db" => "v1-data"}}, fn ->
    f = open_file("db", access: Access.ReadWrite)?
    defer File.close_quietly(f)
    File.write_at(f, 0, String.to_bytes("v2"))?
    File.close(f)
end)

assert patched.value == Ok(Unit)
assert testing.text(patched, "/work/db") == Some("v2-data")
assert patched.open == []
fn within<T>(dir: String, body: () -> Result<T, Error>) -> Result<T, Error>

Runs body with every std::fs call in it, and in the tasks it starts, confined to the directory dir. Inside, a relative path is under dir, an absolute path must be under it, and fs.current_dir() returns dir made absolute. A path that leads outside it, by .. or through a symlink, is InvalidPath instead of reaching what is there, with the reason the path leads outside the directory fs.within confines calls to. An absolute symlink is refused for the same reason, wherever it points. On the operating system’s file system each name is resolved under the directory as it is opened, so a symlink changed during the call cannot lead out either. fs.make_temp_dir is Unsupported{operation: "fs.make_temp_dir", target: "fs.within"}, since its directory is elsewhere. A within inside another confines the call further. A dir that is missing is NotFound, and one that is not a directory is an error too (NotADirectory in memory).

It is how a program handles paths it was given (an archive’s entries, a request’s file name) without reaching files it did not mean to. On the disk it is Go’s os.Root; in memory, the same rules.

fn extract(dest: String, entries: List<(String, Bytes)>) -> Result<Unit, io.Error>
    fs.within(dest, fn ->
        Iter.each(entries, fn (name, data) -> fs.write(name, data))
        Ok(Unit)
    end)
end
import std::fs::testing.{self, Sandbox}

ran = testing.run(Sandbox{files: {"secret.txt" => "s", "site/index.html" => "<p>"}}, fn ->
    within("site", fn -> Ok([read_text("index.html"), read_text("../secret.txt")]))
end)

escaped = Error.InvalidPath{
    path:   "../secret.txt",
    reason: "the path leads outside the directory fs.within confines calls to",
}

assert ran.value == Ok([Ok("<p>"), Err(escaped)])
fn list(dir: String) -> Result<List<Entry>, Error>

The entries of the directory dir, sorted by name, so a listing is the same on every file system and every run. Each Entry’s path is dir and its name joined with /. A symlink is listed as Symlink whatever it points to. An entry whose name is not UTF-8 fails the listing with InvalidPath, naming the entry with U+FFFD in place of each bad sequence.

entries = fs.list("photos")?
import std::fs::testing.{self, Sandbox}

ran = testing.run(Sandbox{files: {"d/b.txt" => "", "d/a.txt" => ""}, dirs: ["d/sub"]}, fn ->
    list("d")
end)

assert ran.value == Ok([
        Entry{path: "d/a.txt", name: "a.txt", kind: Kind.File},
        Entry{path: "d/b.txt", name: "b.txt", kind: Kind.File},
        Entry{path: "d/sub", name: "sub", kind: Kind.Directory},
    ])
fn walk(root: String) -> Iter<Result<Entry, Error>>

Every entry under root, depth first: each directory’s entries in name order, and a directory’s own entries right after it. A symlink is an entry of kind Symlink and is not followed, so a walk never leaves the tree or meets a cycle. Each run of the iterator lists the directories again, as fs.lines reads its file again. A directory that cannot be listed is an Err item where its entries would be, and the walk goes on with the next entry; a name that is not UTF-8 is an InvalidPath item.

sources =
    fs.walk("src")
    |> Iter.count_by(fn e -> Result.map(e, fn e -> e.kind == fs.Kind.File) == Ok(True))
import std::fs::testing.{self, Sandbox}

ran = testing.run(Sandbox{
    files: {"d/b.txt" => "", "d/a/x.txt" => ""},
    links: {"d/c" => "a"},
}, fn ->
    walk("d") |> Iter.map(fn e -> Result.map(e, fn e -> e.path)) |> Iter.to_list()
end)

assert ran.value == [Ok("d/a"), Ok("d/a/x.txt"), Ok("d/b.txt"), Ok("d/c")]

assert testing.run(Sandbox{}, fn -> Result.collect(walk("none"))).value
    == Err(Error.NotFound{path: "none"})
fn glob(pattern: String) -> Result<List<String>, Error>

The paths that match pattern, sorted. In a name, * matches any run of characters, ? any one and [abc] one of a set; a ** name matches any number of directories, none included. A name that starts with . matches only a pattern name that starts with .. This is path.matches’s rule, applied to the paths fs.walk finds under the longest part of the pattern with no wildcard, so a symlink matches as itself and is not followed. A pattern with no ** is matched no deeper than it reaches. A pattern with no wildcard returns the path when something is there. Nothing under a missing directory is Ok([]).

sources = fs.glob("src/**/*.nomi")?
import std::fs::testing.{self, Sandbox}

files = {
    "src/main.nomi"    => "",
    "src/lib/a.nomi"   => "",
    "src/lib/a.txt"    => "",
    "src/.hidden.nomi" => "",
}

ran = testing.run(Sandbox{files:}, fn ->
    [glob("src/**/*.nomi"), glob("src/*.nomi"), glob("src/lib/a.txt"), glob("none/*")]
end)

assert ran.value == [
    Ok(["src/lib/a.nomi", "src/main.nomi"]),
    Ok(["src/main.nomi"]),
    Ok(["src/lib/a.txt"]),
    Ok([]),
]
fn create_dir(path: String, parents: Bool = False) -> Result<Unit, Error>

Makes the directory path. Its parent must exist unless parents is True, which makes every missing directory above it too and succeeds when the directory is already there. Without parents an existing directory is AlreadyExists, and a file at path is AlreadyExists either way.

fs.create_dir("out/2026", parents: True)?
import std::fs::testing.{self, Sandbox}

ran = testing.run(Sandbox{}, fn ->
    [create_dir("a/b"), create_dir("a/b", parents: True), create_dir("a")]
end)

assert ran.value == [
    Err(Error.NotFound{path: "a"}),
    Ok(Unit),
    Err(Error.AlreadyExists{path: "a"}),
]
fn remove(path: String) -> Result<Unit, Error>

Removes a file, a symlink or an empty directory. A directory with entries is DirectoryNotEmpty; fs.remove_all removes it and what it holds.

fs.remove("old.txt")?
import std::fs::testing.{self, Sandbox}

ran = testing.run(Sandbox{files: {"d/x" => ""}}, fn ->
    [remove("d"), remove("d/x"), remove("d"), remove("d")]
end)

assert ran.value == [
    Err(Error.DirectoryNotEmpty{path: "d"}),
    Ok(Unit),
    Ok(Unit),
    Err(Error.NotFound{path: "d"}),
]
fn remove_all(path: String) -> Result<Unit, Error>

Removes path and everything under it, following no symlink in it. Nothing at the path is Ok.

fs.remove_all("build")?
import std::fs::testing.{self, Sandbox}

ran = testing.run(Sandbox{files: {"build/a/b.o" => "", "keep.txt" => ""}}, fn ->
    [remove_all("build"), remove_all("build")]
end)

assert ran.value == [Ok(Unit), Ok(Unit)]
assert ran.files == {"/work/keep.txt" => String.to_bytes("")}
fn remove_all_quietly(path: String) -> Unit

Removes path and everything under it, as fs.remove_all does, and ignores the outcome: the form for a defer after fs.make_temp_dir.

defer fs.remove_all_quietly(dir)
import std::fs::testing.{self, Sandbox}

ran = testing.run(Sandbox{files: {"build/a.o" => ""}}, fn -> remove_all_quietly("build"))

assert ran.files == {}
fn rename(from: String, to: String) -> Result<Unit, Error>

Moves from to to, replacing a file at to. A symlink at from is moved, rather than what it points to.

fs.rename("draft.txt", "final.txt")?
import std::fs::testing.{self, Sandbox}

ran = testing.run(Sandbox{files: {"a.txt" => "a", "b.txt" => "b"}}, fn ->
    rename("a.txt", "b.txt")
end)

assert ran.value == Ok(Unit)
assert ran.files == {"/work/b.txt" => String.to_bytes("a")}
fn copy(from: String, to: String) -> Result<Unit, Error>

Copies the file at from to to, replacing a file at to. A symlink at from is read through.

fs.copy("config.toml", "config.toml.bak")?
import std::fs::testing.{self, Sandbox}

ran = testing.run(Sandbox{files: {"a.txt" => "a"}}, fn -> copy("a.txt", "b.txt"))
assert ran.value == Ok(Unit)
assert testing.text(ran, "/work/b.txt") == Some("a")
fn metadata(path: String) -> Result<Metadata, Error>

What is at path, following symlinks. The modification time is the file system’s, exactly, whatever its year.

size = (fs.metadata("big.bin")?).size
import std::fs::testing.{self, Sandbox}

ran = testing.run(Sandbox{files: {"a.txt" => "four"}}, fn ->
    m = metadata("a.txt")?
    Ok((m.kind, m.size))
end)

assert ran.value == Ok((Kind.File, 4))
fn link_metadata(path: String) -> Result<Metadata, Error>

What is at path, a symlink described as itself rather than as what it points to, which fs.metadata follows. A symlink’s size is its target’s length in bytes.

is_link = (fs.link_metadata("current")?).kind == .Symlink
import std::fs::testing.{self, Sandbox}

ran = testing.run(Sandbox{files: {"a.txt" => "four"}, links: {"b" => "a.txt"}}, fn ->
    followed = metadata("b")?
    link = link_metadata("b")?
    Ok((followed.kind, followed.size, link.kind, link.size))
end)

assert ran.value == Ok((Kind.File, 4, Kind.Symlink, 5))
fn create_symlink(path: String, target: String) -> Result<Unit, Error>

Makes a symlink at path that points to target, as written: a relative target is resolved from the symlink’s own directory when the link is followed, not from the working directory. The target need not exist. Something already at path is AlreadyExists.

fs.create_symlink("current", target: "releases/2026-10")?
import std::fs::testing.{self, Sandbox}

ran = testing.run(Sandbox{files: {"releases/v2/app" => "v2"}}, fn ->
    create_symlink("current", target: "releases/v2")?
    Ok((read_text("current/app"), create_symlink("current", target: "x")))
end)

assert ran.value == Ok((Ok("v2"), Err(Error.AlreadyExists{path: "current"})))
fn read_link(path: String) -> Result<String, Error>

The target of the symlink at path, as it was written. Something that is not a symlink is Other with the code EINVAL.

release = fs.read_link("current")?
import std::fs::testing.{self, Sandbox}

ran = testing.run(Sandbox{files: {"a.txt" => ""}, links: {"b" => "a.txt"}}, fn ->
    [read_link("b"), read_link("a.txt")]
end)

assert ran.value == [
    Ok("a.txt"),
    Err(Error.Other{operation: "readlink", path: "a.txt", code: "EINVAL"}),
]
fn set_mode(path: String, mode: Int) -> Result<Unit, Error>

Sets the permission bits of what path names, following a symlink: 0o644, 0o755, from 0 to 0o777; any other mode is Other with the code EINVAL. Windows keeps only the owner’s write bit, so a file reads back as 0o666 or 0o444. In memory (the browser, a sandbox) the bits are kept and returned by fs.metadata, but nothing is refused for them.

fs.set_mode("deploy.sh", 0o755)?
import std::fs::testing.{self, Sandbox}

ran = testing.run(Sandbox{files: {"run.sh" => ""}}, fn ->
    set_mode("run.sh", 0o755)?
    Ok((metadata("run.sh")?).mode)
end)

assert ran.value == Ok(0o755)
fn exists(path: String) -> Result<Bool, Error>

Whether something is at path. It returns a Result because a refusal (PermissionDenied) is not absence: only NotFound is Ok(False).

if fs.exists("config.toml")? then ...
import std::fs::testing.{self, Sandbox}

ran = testing.run(Sandbox{files: {"a.txt" => ""}}, fn ->
    [exists("a.txt"), exists("b.txt"), exists(".")]
end)

assert ran.value == [Ok(True), Ok(False), Ok(True)]
fn temp_dir() -> String

The directory temporary files go in: the operating system’s (/tmp, or what TMPDIR names), or /tmp in memory. A wasip1 module reaches only the directories its runtime preopens, so there it is the first of TMPDIR, /tmp and the working directory that is preopened, and /tmp when none is.

fs.temp_dir() // "/tmp"
import std::fs::testing.{self, Sandbox}

assert testing.run(Sandbox{}, fn -> temp_dir()).value == "/tmp"
fn make_temp_dir() -> Result<String, Error>

Makes a fresh directory under fs.temp_dir() and returns its path. Defer fs.remove_all_quietly on the next line, so the directory and everything in it is removed however the function ends. It is how a test exercises the real file system; a named temporary file is fs.create(path.join(dir, "x"), mode: .New) inside it. In a wasip1 module whose runtime preopened none of those directories it returns Err(io.Error.Unsupported{operation: "fs.make_temp_dir", target: "wasip1/wasm with no preopened directory (TMPDIR, /tmp or the working directory)"}).

dir = fs.make_temp_dir()?

defer fs.remove_all_quietly(dir)
import std::fs::testing.{self, Sandbox}

fn scratch() -> Result<String, Error>
    dir = make_temp_dir()?
    defer remove_all_quietly(dir)
    write_text("${dir}/x.txt", "x")?
    read_text("${dir}/x.txt")
end

ran = testing.run(Sandbox{}, scratch)

assert ran.value == Ok("x")
assert ran.files == {}
fn current_dir() -> Result<String, Error>

The directory relative paths are resolved against: the program’s working directory, or the sandbox’s (/work by default). There is no way to change it, since it would change what every relative path in every task means.

here = fs.current_dir()?
import std::fs::testing.{self, Sandbox}

assert testing.run(Sandbox{cwd: "/home/ada"}, fn -> current_dir()).value == Ok("/home/ada")