Browse packages

Package · v0.42.0 · changelog

fs

Standard library filesystem

Runtime support

  • Node
  • Deno
  • Bun
  • Browser

Browser: Imports safely, but filesystem operations are unavailable.

This module provides filesystem access through a Python pathlib-inspired API, including file operations, directory traversal, and project discovery.

File-system routing is owned by consuming frameworks rather than this package. Primate applications use the routing implementation provided by @primate/core.

Installation#

bash
npm install @rcompat/fs
bash
pnpm add @rcompat/fs
bash
yarn add @rcompat/fs
bash
bun add @rcompat/fs

Usage#

FileRef#

A pathlib-like class for file and directory operations.

Creating a FileRef#

js
import fs from "@rcompat/fs";

const file = fs.ref("./src/config.json"); // FileRef("./src/config.json")
const absolute = fs.ref("/etc/hosts");    // FileRef("/etc/hosts")
const from_url = fs.ref(new URL("file:///tmp/config.json"));

// resolve relative to cwd
const resolved = fs.resolve("./src");

The exported Path type is the canonical complete-path input for FileRef and filesystem helpers: string | URL | FileRef. Native path strings and file:// strings are accepted. Strings beginning with a non-file <scheme>://, such as https://example.com/file.txt, are rejected before filesystem access; drive-letter paths (including doubled forward slashes such as C://Temp/file.txt) and ordinary filenames containing a colon remain native paths. URL objects must use the file: protocol. Filesystem helpers never fetch network resources. join() takes only relative strings or relative FileRefs: absolute, drive-qualified, and URL operands are rejected. Complete file URLs are accepted by fs.ref() and other complete-path inputs, not by join(). Empty join operands do nothing.

Path manipulation#

js
import fs from "@rcompat/fs";

const file = fs.ref("./src/components/Button.tsx");

file.path; // "./src/components/Button.tsx"
file.name; // "Button.tsx"
file.base; // "Button"
file.extension; // ".tsx"
file.parent(); // FileRef("./src/components")
file.webpath(); // "./src/components/Button.tsx" (forward slashes)
file.toURL(); // URL("file:///current/directory/src/components/Button.tsx")

// join paths
file.parent().join("Input.tsx"); // FileRef("./src/components/Input.tsx")

const route = fs.ref("./src/../assets");
route.path;                      // "./src/../assets" (spelling retained)
route.join("./icons").path;     // "./src/../assets/./icons"
route.normalize().path;         // "assets" (explicit lexical normalization)
route.isAbsolute();             // false
route.relativeTo("./src");     // "../assets" (portable / separators)
fs.relativeTo(route, "./src"); // same result

toURL() synchronously converts the reference with the running host's native file-URL semantics. Relative paths are resolved from the current working directory, and reserved characters are escaped without changing their literal filesystem meaning. Use .href when a URL string is required. Browser bundles remain safe to import, but calling toURL() in a browser throws fs is not available in the browser.

relativeTo(base) compares lexical locations, not filesystem identities. It returns "." for the same location and throws on incompatible roots or when an implicit cwd or Windows drive context would be needed. It is not a containment or symlink-security check. Windows drive letters compare without case while ordinary components retain their spelling and case. fs.resolve() still explicitly resolves against cwd; it does not resolve symlinks.

Migrating from @rcompat/path#

The separate @rcompat/path workspace has been removed. Use the existing filesystem-reference operations without opening or accessing a file:

js
import fs from "@rcompat/fs";

fs.ref("a//b/../c/").normalize().webpath(); // "a/c/"
fs.ref("/app/routes").isAbsolute(); // true
fs.ref("app/assets/logo.svg").relativeTo("app/routes");
// "../assets/logo.svg"

Replace path.posix.normalize(value) with fs.ref(value).normalize().path, path.posix.isAbsolute(value) with fs.ref(value).isAbsolute(), and path.relative(base, target) with fs.ref(target).relativeTo(base).

This is a migration, not an identical compatibility layer. On servers, these operations use the running host's native path syntax, not a selectable POSIX or foreign Windows dialect. Browser references use slash syntax and preserve literal backslashes. relativeTo returns "." rather than "" for equal paths and throws for incompatible roots or relationships requiring implicit context, rather than returning the normalized target. Its result always uses /.

Previously published @rcompat/path artifacts are unaffected. There is no forwarding package or new filesystem API associated with this removal.

Reading files#

js
import fs from "@rcompat/fs";

const file = fs.ref("./config.json");

// read as text
const text = await file.text();

// read and parse JSON
const config = await file.json();

// read as binary
const bytes = await file.bytes(); // Uint8Array
const buffer = await file.arrayBuffer(); // ArrayBuffer

// read as stream
const stream = file.stream();

// get file size
const size = await file.size();

Opening a file for streaming#

Use fs.open(path) or file.open() to get an OpenFile with the byte size and single-use readable stream from the same open handle. Symbolic links to regular files are followed. Missing files retain their filesystem error code, and directories and other non-regular files are rejected. Browser imports are safe, and both methods reject when called in a browser.

js
import fs from "@rcompat/fs";

const file = await fs.open("./artifact.bin");
const response = new Response(file.readable, {
  headers: { "content-length": String(file.size) },
});

Replacing or unlinking the path after opening leaves the stream reading the original file. In-place writes can still change its contents and length. The caller owns the handle until the stream reaches EOF, is cancelled, or encounters a read error. Call await file.close() if you abandon the stream or stop reading early. Closing ends the stream and can be called repeatedly, including after automatic cleanup.

Writing files#

js
import fs from "@rcompat/fs";

const file = fs.ref("./output.txt");

// write text (auto-adds trailing newline)
await file.write("Hello, world!");

// write JSON (pretty-printed)
await file.writeJSON({ name: "example", version: "1.0.0" });

// write binary
await file.write(new Uint8Array([0x48, 0x69]));

Setting file permissions#

ts
const script = fs.ref("./entrypoint.sh");
await script.write("#!/bin/sh\nexit 0");
await script.chmod(0o755);
await script.chmod(0o644);

await file.chmod(mode) sets the permission bits of an existing regular file on POSIX with Node, Deno, or Bun. It accepts integers from 0o000 through 0o777. Directories, symbolic links (including dangling links), and missing files are rejected. Filesystem errors propagate to the caller. Calls on Windows and in browsers reject.

When the file can be opened for reading or writing, the operation opens it without following a final symlink and changes the mode through that handle. If access permissions prevent opening the file, the operation checks the path again and then changes the mode by path. A symlink substituted between that check and the change can be followed. Use this method only where you control the directory entries in the path. Parent symlinks are resolved normally.

File info#

js
import fs from "@rcompat/fs";

const file = fs.ref("./src");

await file.exists(); // true/false
await file.empty(); // true for zero-byte files and directories without entries
await file.modified(); // modification time (ms)
await file.type(); // "file" | "directory" | "link" | null

empty() follows symbolic links. Missing paths and broken links return false. It is also available as fs.empty(path).

Directory operations#

js
import fs from "@rcompat/fs";

const src = fs.ref("./src");

// list directory contents
const files = await src.files();

// list with filter (shallow, non-recursive)
const ts_files = await src.files({ filter: info => info.extension === ".ts" });

// recursive, with regex matcher
const all_ts_files = await src.files({
  recursive: true,
  filter: /\.ts$/
});

const dir = await fs.directory.create("./dist/assets");
await dir.copy(fs.ref("./backup"));
await dir.remove();
js
import fs from "@rcompat/fs";

const dir = await fs.directory.create("./dist/assets", { mode: 0o755 });
const empty = await fs.file.create(dir.join("empty.txt"));
const current = await fs.link.create(dir.join("current"), "../releases/v2", {
  type: fs.SoftLink,
  targetType: "directory",
});

Each creation method resolves to a FileRef. Directories are recursive by default. Set recursive: false to require existing parents and a new directory. fs.file.create(path) creates an empty file exclusively and requires an existing parent. An occupied path, including a dangling symlink, causes it to fail. FileRef.write() continues to create missing parent directories.

Use fs.directory.create(parent, { temporary: true, prefix: "stage-" }) to atomically create a unique directory in an existing parent. Pass undefined for the system temporary directory. The prefix defaults to "rcompat-" and must be a filename prefix without path separators. The returned reference points to the directory actually created. Temporary directories are created with owner-only permissions where supported. The caller owns cleanup.

Symbolic links are the default. A string or FileRef target is stored with its original spelling, and a relative target is interpreted from the link's directory. Targets may be missing. targetType: "file" | "directory" supplies the target-kind hint for Windows, where symlink creation may also require privileges. Use paths or references for symbolic targets and pass a file URL when needed for the destination.

Use ref.parent() to navigate to a lexical parent. It works synchronously and is available in browsers. A bare relative filename returns . and a filesystem root returns itself. Disk operations throw when called in a browser.

Publishing a staged file durably#

js
const staged = fs.ref("./artifacts/staging/upload");
const destination = fs.ref("./artifacts/digest");
await staged.sync();
await fs.link.create(destination, staged, { type: fs.HardLink });
await destination.parent().sync();

A hard link creates a new name for the same filesystem entry in one operation. A relative hard-link source resolves from the working directory. Both parent directories must already exist and the source and destination must be on the same filesystem. A collision, including one caused by another publisher, rejects with error.code === "EEXIST" and leaves the existing entry untouched. The caller manages staging and cleanup.

FileRef.sync() requests a native flush of file contents and metadata for a regular file, or of directory entries for a directory. Use fs.sync(path) when starting from a path string or file URL. Both reject symbolic links. Sync the file after all writes complete, then sync its destination directory after linking. If the destination directory was newly created, sync its containing directory as well to persist that name. Crash durability depends on the filesystem, operating system and storage honoring these flushes. Unsupported operations reject with the runtime's filesystem error, such as EINVAL, ENOTSUP or EPERM. A directory sync failure after linking leaves the published entry visible without confirmation of durability.

Permission bits, append and timestamps#

FileRef.mode() returns the entry's POSIX permission bits. FileRef.write(data, { mode: 0o600 }) and FileRef.appendBytes(data, { mode: 0o600 }) apply the mode when creating a file. Existing entries keep their mode. With fs.directory.create(), the mode applies to new directories. Modes are integers from 0o000 through 0o777. Creation modes are subject to the process umask. Windows rejects explicit POSIX modes, mode(), and chmod().

appendBytes() takes a Uint8Array, appends at EOF using native append semantics, and creates a missing file in an existing parent. Concurrent writers do not overwrite existing bytes. Large appends can involve multiple writes and may interleave. append(suffix) continues to append to the path.

FileRef.setModified(time) accepts a Date or Unix milliseconds. It preserves the access time to the precision supported by the runtime and filesystem. It reads access time before updating timestamps, so concurrent access-time changes may race with the update. modified() returns rounded Unix milliseconds. Symbolic links are updated directly where supported.

Other methods#

js
import fs from "@rcompat/fs";

const file = fs.ref("./src/utils.ts");

// generate content hash
const hash = await file.hash(); // SHA-256 by default
const sha512 = await file.hash("SHA-512");

// dynamic import
const module = await file.import();
const func = await file.import("default");

// find project root (walks up looking for package.json)
const root = await file.discover("package.json");

Lazy glob scanning#

fs.glob() lazily yields matching files as absolute FileRef values beneath a resolved working directory:

js
import fs from "@rcompat/fs";

const controller = new AbortController();
for await (const file of fs.glob("src/**/*.ts", {
  cwd: ".",
  signal: controller.signal,
})) {
  console.log(file.path);
}

The portable pattern syntax supports *, ?, ** as a complete path segment, and bracket classes such as [a-z] and [!0-9]. Patterns are relative to cwd and always use / separators. Absolute patterns, . and .. segments, brace expansion, extglobs, and backslash separators are rejected.

Wildcards do not match path segments beginning with . unless that segment is explicitly written with a leading dot. Symbolic links are neither followed nor returned, preventing loops and traversal outside the root. Missing or non-directory roots yield nothing; inaccessible roots and other I/O failures reject iteration. Results retain native directory iteration order, which is not guaranteed to be sorted. Iteration stops scanning after consumer exit and an abort signal is checked throughout traversal. Browser imports remain safe, but calling fs.glob() there throws fs is not available in the browser.

Project utilities#

js
import fs from "@rcompat/fs";

// find project root directory
const project_root = await fs.cwd().discover("package.json");
// FileRef("/path/to/project")

// get path to package.json
const package_json = project_root.join("package.json");
// FileRef("/path/to/project/package.json")

Verified streamed snapshots#

fs.spool() copies a byte stream once to a private disposable file while incrementally computing SHA-256. It applies backpressure and does not buffer the complete input. When expectedDigest is supplied, it returns only after the saved bytes match that trusted digest; a mismatch, abort, or read/write failure removes the partial file and rejects without exposing a snapshot.

js
import fs from "@rcompat/fs";

const snapshot = await fs.spool(upstream.body, {
  expectedDigest: trusted_digest,
  signal: request.signal,
});

return new Response(snapshot.stream(), {
  headers: { "content-length": String(snapshot.size) },
});

Pass maxBytes to set an inclusive limit in bytes. It must be a non-negative safe integer. If the next chunk would exceed the limit, fs.spool() rejects with code spool_limit_exceeded before writing that chunk and removes the staging directory. Omit the option for an unbounded snapshot.

The caller owns the snapshot. Its one-shot stream removes the staging directory after EOF or cancellation. Call await snapshot.dispose() if the stream is not handed to a consumer, or to terminate an active read. Do not dispose immediately after constructing a streaming response; its host must finish or cancel the response body. Without expectedDigest, snapshot.digest is computed but not externally verified. Browser bundles are safe to import, but this disk-backed operation is unsupported in browsers and throws when called.

By default, spool creates its private staging directory under the system temporary directory. Supply an existing directory as parent to stage on the destination filesystem. Treat the contents of the read-only snapshot.file reference as immutable so the saved digest and size still describe the file. Publish the hard link before streaming or disposing the snapshot. Cleanup removes the staging path and leaves the published link intact.

js
import fs from "@rcompat/fs";

const snapshot = await fs.spool(upload, {
  parent: destination.parent(),
  maxBytes: 128 * 1024 * 1024,
});

try {
  await fs.link.create(destination, snapshot.file, { type: fs.HardLink });
} finally {
  await snapshot.dispose();
}

Streamable values#

The root API recognizes blobs, readable streams, and objects implementing the shared fs.streamable protocol. The symbol uses the global registry key std:symbol/stream, so separately loaded package copies share the same identity.

js
import fs from "@rcompat/fs";

// check if a value is streamable
if (fs.isStream(value)) {
  const stream = fs.stream(value);
}

// check if named (has a name property)
if (fs.isNamedStream(value)) {
  console.log(value.name);
}

// provide a stream through the shared protocol
const source = {
  [fs.streamable]() {
    return new ReadableStream();
  },
};

Migrate existing implementations from [symbol.stream]() to [fs.streamable](). Both properties address the same global symbol during the migration, so old and new consumers remain interoperable.

Examples#

Build script#

js
import fs from "@rcompat/fs";

const src = fs.ref("./src");
const dist = fs.ref("./dist");

// clean dist
await dist.remove();

// copy source files
await src.copy(dist, info => info.extension !== ".test.ts");

// process each file
for (const file of await dist.list()) {
  const content = await file.text();
  const transformed = content.replaceAll("__DEV__", "false");
  await file.write(transformed);
}

Config loader#

js
import fs from "@rcompat/fs";

async function loadConfig() {
  const root = await fs.cwd().discover("package.json");
  const config_path = root.join("config.json");

  if (await config_path.exists()) return config_path.json();

  return { /* defaults */ };
}

Asset fingerprinting#

js
import fs from "@rcompat/fs";

async function fingerprint(file) {
  const hash = await file.hash();
  const name = `${file.base}.${hash}${file.extension}`;
  return file.parent().join(name);
}

const original = fs.ref("./dist/bundle.js");
const fingerprinted = await fingerprint(original);
await original.copy(fingerprinted);

Cross-Runtime Compatibility#

Runtime Supported
Node.js ✓
Deno ✓
Bun ✓
Browser Lexical references only; filesystem operations unsupported

Browser bundles can safely import the package. fs.ref(), fs.join(), fs.normalize(), fs.relativeTo(), fs.isAbsolute(), and reference methods that manipulate path text work with slash-based paths without guessing the host OS. Backslashes are literal characters. fs.isRef() recognizes browser references; stream predicates return false. Disk and cwd-dependent operations throw a clear error when called.

License#

MIT

Contributing#

See CONTRIBUTING.md in the repository root.