Browse API packages

API · v0.35.3

fs

Standard library filesystem

Member signatures use schematic object.member(...) API notation. Exported type declarations are valid TypeScript.

Portable filesystem operations and FileRef construction.

Node, Deno, and Bun use native filesystem implementations. Browser bundles are safe to import: the three predicate functions return false, while operations that require filesystem access throw fs is not available in the browser when called.

ts
import fs from "@rcompat/fs";
import type {
  DirectoryOptions, FileInfo, FileRef, FileType, Filter, ListOptions, NamedStreamable, Path, RemoveOptions, Streamable, WritableInput,
} from "@rcompat/fs";

fs.ref#

Creates a FileRef for a filesystem path.

Parameters

  • path — A path string or existing reference.

Returns: A FileRef for the normalized path.

ts
fs.ref(path: Path): FileRef;

Example

ts
const config = fs.ref("config.json");
await config.writeJSON({ enabled: true });
await config.json(); // { enabled: true }

fs.isRef#

Checks whether a value is a compatible FileRef.

Parameters

  • value — The value to inspect.
ts
fs.isRef(value: unknown): value is FileRef;

fs.isStream#

Checks whether a value can provide a readable stream.

Parameters

  • value — The value to inspect.
ts
fs.isStream(value: unknown): value is Streamable;

fs.isNamedStream#

Checks whether a streamable value also has a name.

Parameters

  • value — The value to inspect.
ts
fs.isNamedStream(value: unknown): value is NamedStreamable;

fs.cwd#

Returns the current working directory as an absolute reference.

ts
fs.cwd(): FileRef;

fs.create#

Creates a directory.

Parameters

  • path — Directory path to create.
  • options — Directory creation options.

Default: options.recursive is true.

ts
fs.create(path: Path, options?: DirectoryOptions): Promise<void>;

fs.resolve#

Resolves a path from the current working directory.

Parameters

  • path — Path to resolve, or the current directory when omitted.
ts
fs.resolve(path?: string): FileRef;

fs.list#

Lists immediate or recursive directory entries.

Parameters

  • path — Directory to list.
  • options — Recursion and filtering options.
ts
fs.list(path: Path, options?: ListOptions): Promise<FileRef[]>;

fs.files#

Lists file entries in a directory.

Parameters

  • path — Directory to list.
  • options — Recursion and filtering options.
ts
fs.files(path: Path, options?: ListOptions): Promise<FileRef[]>;

fs.dirs#

Lists directory entries in a directory.

Parameters

  • path — Directory to list.
  • options — Recursion and filtering options.
ts
fs.dirs(path: Path, options?: ListOptions): Promise<FileRef[]>;

fs.exists#

Checks whether a path exists.

ts
fs.exists(path: Path): Promise<boolean>;

fs.empty#

Checks whether a file or directory is empty.

ts
fs.empty(path: Path): Promise<boolean>;

fs.arrayBuffer#

Reads a file into an array buffer.

ts
fs.arrayBuffer(path: Path): Promise<ArrayBuffer>;

fs.bytes#

Reads a file into an unsigned byte array.

ts
fs.bytes(path: Path): Promise<Uint8Array>;

fs.text#

Reads a UTF-8 text file.

ts
fs.text(path: Path): Promise<string>;

fs.json#

Reads and parses a JSON file.

ts
fs.json(path: Path): Promise<JSONValue>;

fs.stream#

Returns a readable stream for a path or streamable value.

ts
fs.stream(target: string | Streamable): ReadableStream<unknown>;

fs.write#

Writes text, bytes, blobs, responses, or readable streams to a path.

ts
fs.write(path: Path, value: WritableInput): Promise<void>;

fs.writeJSON#

Writes a value as indented JSON.

ts
fs.writeJSON(path: Path, value: JSONValue): Promise<void>;

fs.size#

Returns a file's size in bytes.

ts
fs.size(path: Path): Promise<number>;

fs.webpath#

Converts a path to forward-slash separators.

ts
fs.webpath(path: Path): string;

fs.join#

Joins path segments into a new reference.

ts
fs.join(path: Path, ...paths: Path[]): FileRef;

fs.discover#

Walks upward until a directory containing a filename is found.

ts
fs.discover(path: Path, filename: string): Promise<FileRef>;

fs.type#

Returns the filesystem entry type, or null when it is missing.

ts
fs.type(path: Path): Promise<FileType>;

Types#

DirectoryOptions#

Options for creating a directory.

ts
interface DirectoryOptions {
  // Create missing parent directories.
  // Default: `true`
  recursive?: boolean;
}

FileInfo#

Information supplied to directory-entry filters.

ts
type FileInfo = {
  // Native filesystem path for the entry.
  path: string;
  // Final path component including extensions.
  name: string;
  // Last extension including its leading dot.
  extension: string;
  // All extensions beginning at the first dot.
  fullExtension: string;
  // Kind of filesystem entry.
  type: "file" | "directory" | "link";
};

FileRef#

A pathlib-inspired reference to a file or directory.

Construct references through fs.ref() when possible. Methods perform filesystem work only when called; creating a reference does not access disk.

ts
declare class FileRef {}

Constructor#

new FileRef()#

Creates a reference without accessing the filesystem.

ts
constructor(path: Path)

Static methods#

FileRef.is()#

Checks whether a value carries the compatible FileRef brand.

ts
static is(x: unknown): x is FileRef

Instance properties#

file.path#

The normalized native filesystem path.

ts
get path(): string

file.name#

The final path component including its extension.

ts
get name(): string

file.base#

The final path component without its last extension.

ts
get base(): string

file.extension#

The last filename extension including its leading dot.

ts
get extension(): string

file.fullExtension#

All filename extensions beginning at the first dot.

ts
get fullExtension(): string

file.directory#

A reference to the parent directory.

ts
get directory(): FileRef

file.core#

The final path component without any extension.

ts
get core(): string

Instance methods#

file.join()#

Joins path segments to this reference.

ts
join(...paths: Path[]): FileRef

file.webpath()#

Converts native separators to forward slashes.

ts
webpath(): string

file.append()#

Appends text directly to the path.

ts
append(suffix: string): FileRef

file.bare()#

Removes the final extension and optionally appends text.

ts
bare(append?: string): FileRef

file.debase()#

Removes a base path and optional suffix from this path.

ts
debase(base: Path, suffix?: string): FileRef

file.text()#

Reads the file as UTF-8 text.

ts
text(): Promise<string>

file.json()#

Reads and parses the file as JSON.

ts
json<T extends JSONValue>(): Promise<T>

file.bytes()#

Reads the file as bytes.

ts
bytes(): Promise<Uint8Array>

file.arrayBuffer()#

Reads the file into an array buffer.

ts
arrayBuffer(): Promise<ArrayBuffer>

file.stream()#

Opens a readable byte stream for the file.

Pass the result to stream.stringify() to decode UTF-8 text.

ts
stream(): ReadableStream<Uint8Array>

file.size()#

Returns the file size in bytes.

ts
size(): Promise<number>

file.write()#

Writes supported text, binary, blob, response, or stream input.

ts
write(input: WritableInput): Promise<void>

file.writeJSON()#

Writes a value as indented JSON.

ts
writeJSON(input: JSONValue): Promise<void>

file.exists()#

Checks whether the referenced path exists.

ts
exists(): Promise<boolean>

file.type()#

Returns the entry type, or null when the path is missing.

ts
type(): Promise<FileType>

file.modified()#

Returns the modification time as Unix milliseconds.

ts
modified(): Promise<number>

file.empty()#

Checks whether a file has zero bytes or a directory has no entries.

ts
empty(): Promise<boolean>

file.list()#

Lists immediate or recursive directory entries.

ts
list(options?: ListOptions): Promise<FileRef[]>

file.files()#

Lists only file entries.

ts
files(options?: ListOptions): Promise<FileRef[]>

file.dirs()#

Lists only directory entries.

ts
dirs(options?: ListOptions): Promise<FileRef[]>

file.create()#

Creates this directory.

Default: options.recursive is true.

ts
create(options?: DirectoryOptions): Promise<void>

file.remove()#

Removes this path.

Default: Missing paths do not fail unless options.fail is true.

ts
remove(options?: RemoveOptions): Promise<void>

file.copy()#

Copies this file or directory to another reference.

ts
copy(to: FileRef, filter?: Filter): Promise<void>

file.hash()#

Hashes the file contents.

Parameters

  • algorithm — A Web Crypto digest algorithm.

Default: "SHA-256"

ts
hash(algorithm?: string): Promise<string>

file.import()#

Dynamically imports the file, optionally returning one named export.

ts
import(name?: string): Promise<any>

file.discover()#

Walks upward to find a directory containing a filename.

ts
discover(filename: string): Promise<FileRef>

file.sibling()#

Returns a named reference in the same directory.

ts
sibling(name: string): FileRef

file.or()#

Returns this reference when it exists, otherwise a fallback value.

ts
or<T>(fallback: () => T): Promise<this | T>

file.toString()#

Returns the normalized path.

ts
toString(): string

Protocol members#

file[Symbol.replace]()#

Replaces this reference's string value inside another string.

ts
[Symbol.replace](
    string: string,
    replacement: string | StringReplacer,
  ): string

file[symbol.stream]()#

Returns the file's stream through @rcompat/symbol.stream.

ts
[symbol.stream](): ReadableStream<Uint8Array>

file[util.inspect.custom]()#

Formats the reference for Node-compatible object inspection.

ts
[util.inspect.custom](): string

file.Name protocol property#

The stable class name used by rcompat protocols.

ts
get Name(): "FileRef"

FileType#

The recognized kind of a filesystem entry, or null when it is missing.

ts
type FileType = "directory" | "file" | "link" | null;

Filter#

Selects directory entries synchronously or asynchronously.

Parameters

  • info — Information about the candidate entry.
ts
type Filter = (info: FileInfo) => MaybePromise<boolean>;

ListOptions#

Options for listing directory entries.

ts
type ListOptions = {
  // Visit entries in nested directories.
  // Default: `false`
  recursive?: boolean;
  // Keep entries accepted by a regular expression or callback.
  filter?: RegExp | Filter;
};

NamedStreamable#

A streamable value with a filename or other display name.

Type parameters

  • T — The chunks produced by the stream.
ts
type NamedStreamable<T = unknown> = Streamable<T> & { name: string };

Path#

A filesystem path represented by a string or an existing reference.

ts
type Path = string | FileRef;

RemoveOptions#

Options for removing a filesystem entry.

ts
interface RemoveOptions extends DirectoryOptions {
  // Fail when the entry does not exist.
  // Default: `false`
  fail?: boolean;
  // Remove directory contents recursively.
  // Default: `true`
  recursive?: boolean;
}

Streamable#

A value that can provide a web ReadableStream.

Objects can expose streams through @rcompat/symbol.stream.

Type parameters

  • T — The chunks produced by the stream.
ts
type Streamable<T = unknown> =
  | Blob
  | ReadableStream<T>
  | { [symbol.stream](): ReadableStream<T> }
  ;

WritableInput#

Content accepted by filesystem write operations.

ts
type WritableInput =
  | ArrayBuffer
  | Uint8Array
  | Blob
  | ReadableStream
  | Response
  | string
  ;