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): stringwriteFileSync(path: string, data: string): voidreadFileSync 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): booleanstatSync(path: string): StatsstatSync 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 filerenameSync(oldPath: string, newPath: string): void // rename / moveFull reference
| Function | Returns | Throws on |
|---|---|---|
readFileSync(path) | string | open/read error |
writeFileSync(path, data) | void | create/write error |
appendFileSync(path, data) | void | open/write error |
copyFileSync(src, dest) | void | read/write error |
existsSync(path) | boolean | — |
accessSync(path) | void | not accessible |
statSync(path) | Stats | stat error |
lstatSync(path) | Stats | stat error (does not follow symlinks) |
realpathSync(path) | string | resolve error |
readdirSync(path) | string[] | open/read error |
readdirTypesSync(path) | Dirent[] | open/read error |
mkdirSync(path) | void | mkdir error |
mkdirpSync(path) | void | mkdir error (recursive; no-op if it exists) |
rmSync(path, recursive) | void | remove error |
rmdirSync(path) | void | rmdir error (must be empty) |
unlinkSync(path) | void | unlink error |
renameSync(old, new) | void | rename error |
chmodSync(path, mode) | void | chmod error (mode e.g. 420 = 0o644) |
truncateSync(path, length) | void | truncate error |
readdirTypesSync returns Dirent[], each with .name, .isFile(), and .isDirectory() (Node’s
withFileTypes option). rmSync(path, true) removes a directory tree recursively.