Skip to content

File System (@std/fs)

@std/fs provides synchronous file I/O, bound directly to libc/POSIX. Import the functions you need:

import { readFileSync, writeFileSync, existsSync } from "@std/fs";
writeFileSync("/tmp/note.txt", "hello");
if (existsSync("/tmp/note.txt")) {
console.log(readFileSync("/tmp/note.txt")); // "hello"
}

Reading & writing

readFileSync(path: string): string
writeFileSync(path: string, data: string): void

readFileSync reads the whole file (streaming in chunks, so pipes and /proc files work too) and throws on an open/read error. writeFileSync creates or truncates the file (mode 0644), writing all bytes, and throws if the write fails.

Existence & metadata

existsSync(path: string): boolean
statSync(path: string): Stats

statSync returns a Stats object:

import { statSync, Stats } from "@std/fs";
let s: Stats = statSync("/tmp/note.txt");
console.log(s.size); // size in bytes (i64)
console.log(s.mtime); // modification time, unix seconds (i64)
if (s.isFile()) { /* ... */ }
if (s.isDirectory()) { /* ... */ }

Directories

mkdirSync(path: string): void // create a directory (mode 0755)
readdirSync(path: string): string[] // entry names, excluding "." and ".."
import { readdirSync } from "@std/fs";
let entries: string[] = readdirSync("/tmp");
let i: i32 = 0;
while (i < entries.length) {
console.log(entries[i]);
i = i + 1;
}

Removing & moving

unlinkSync(path: string): void // delete a file
renameSync(oldPath: string, newPath: string): void // rename / move

Full reference

FunctionReturnsThrows on
readFileSync(path)stringopen/read error
writeFileSync(path, data)voidcreate/write error
appendFileSync(path, data)voidopen/write error
copyFileSync(src, dest)voidread/write error
existsSync(path)boolean
accessSync(path)voidnot accessible
statSync(path)Statsstat error
lstatSync(path)Statsstat error (does not follow symlinks)
realpathSync(path)stringresolve error
readdirSync(path)string[]open/read error
readdirTypesSync(path)Dirent[]open/read error
mkdirSync(path)voidmkdir error
mkdirpSync(path)voidmkdir error (recursive; no-op if it exists)
rmSync(path, recursive)voidremove error
rmdirSync(path)voidrmdir error (must be empty)
unlinkSync(path)voidunlink error
renameSync(old, new)voidrename error
chmodSync(path, mode)voidchmod error (mode e.g. 420 = 0o644)
truncateSync(path, length)voidtruncate error

readdirTypesSync returns Dirent[], each with .name, .isFile(), and .isDirectory() (Node’s withFileTypes option). rmSync(path, true) removes a directory tree recursively.