fs
std/fs — files and directories.
Native and, in time, WASI. Unavailable on the web, which is not an oversight and not a limitation to be worked around: a page has no filesystem, and a shim that pretended otherwise — local storage dressed up as a disk — would be a different thing wearing the same name. A program that reads a file is a program that does not run in a browser, and it should find that out when it runs rather than when it silently reads nothing.
Every call that can fail returns (T, error). There is no exception to catch and no errno to inspect: what went wrong arrives as a message, in the same shape as everything else in this library.
The host implements one object called fs. A runtime that does not — the browser — leaves it unimplemented, and a call traps with a message naming the function, which is the honest failure for asking a page for a file.
read
pub fn read(path: str) -> (str, error)
The whole of a file, as text.
Text, not bytes: str is what crosses the boundary, and a file that is not valid UTF-8 is an error rather than a string of replacement characters — silently substituting them is how a binary file becomes corrupt data that looks fine.
write
pub fn write(path: str, body: str) -> error
Write body to path, replacing whatever was there.
The directory above it must exist. Creating parents silently is the kind of convenience that writes a file where nobody meant to put one.
list
pub fn list(path: str) -> ([str], error)
The names in a directory, without . and .., in the order the host gives them — which is not sorted, on any platform worth relying on.
remove
pub fn remove(path: str) -> error
Delete a file, or an empty directory.
It will not delete a directory that has anything in it. Recursive deletion is one typo away from catastrophe and is not something a standard library should make a one-liner.
Kind
enum Kind
What is at a path.
MissingFileDirectory
kind
pub fn kind(path: str) -> Kind
exists
pub fn exists(path: str) -> bool
Whether anything is at a path.
A convenience over [kind], and one to use sparingly: between asking and acting, the answer may have changed. Prefer doing the thing and handling the error.
is_file
pub fn is_file(path: str) -> bool
is_dir
pub fn is_dir(path: str) -> bool
temp_dir
pub fn temp_dir() -> str
The directory this host puts temporary files in, without a trailing separator.
Asked of the host rather than assumed, because /tmp is a POSIX convention and not a fact: Windows has no such directory, and a test that hard-codes one passes on two platforms and fails on the third. Paths below it may be joined with /, which every platform this runs on accepts — including Windows, whose API takes either separator.