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.
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.
Example
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.
fs.isRef(value: unknown): value is FileRef;fs.isStream#
Checks whether a value can provide a readable stream.
Parameters
value— The value to inspect.
fs.isStream(value: unknown): value is Streamable;fs.isNamedStream#
Checks whether a streamable value also has a name.
Parameters
value— The value to inspect.
fs.isNamedStream(value: unknown): value is NamedStreamable;fs.cwd#
Returns the current working directory as an absolute reference.
fs.cwd(): FileRef;fs.create#
Creates a directory.
Parameters
path— Directory path to create.options— Directory creation options.
Default: options.recursive is true.
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.
fs.resolve(path?: string): FileRef;fs.list#
Lists immediate or recursive directory entries.
Parameters
path— Directory to list.options— Recursion and filtering options.
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.
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.
fs.dirs(path: Path, options?: ListOptions): Promise<FileRef[]>;fs.exists#
Checks whether a path exists.
fs.exists(path: Path): Promise<boolean>;fs.empty#
Checks whether a file or directory is empty.
fs.empty(path: Path): Promise<boolean>;fs.arrayBuffer#
Reads a file into an array buffer.
fs.arrayBuffer(path: Path): Promise<ArrayBuffer>;fs.bytes#
Reads a file into an unsigned byte array.
fs.bytes(path: Path): Promise<Uint8Array>;fs.text#
Reads a UTF-8 text file.
fs.text(path: Path): Promise<string>;fs.json#
Reads and parses a JSON file.
fs.stream#
Returns a readable stream for a path or streamable value.
fs.stream(target: string | Streamable): ReadableStream<unknown>;fs.write#
Writes text, bytes, blobs, responses, or readable streams to a path.
fs.write(path: Path, value: WritableInput): Promise<void>;fs.writeJSON#
Writes a value as indented JSON.
fs.size#
Returns a file's size in bytes.
fs.size(path: Path): Promise<number>;fs.webpath#
Converts a path to forward-slash separators.
fs.webpath(path: Path): string;fs.join#
Joins path segments into a new reference.
fs.discover#
Walks upward until a directory containing a filename is found.
fs.type#
Returns the filesystem entry type, or null when it is missing.
Types#
DirectoryOptions#
Options for creating a directory.
interface DirectoryOptions {
// Create missing parent directories.
// Default: `true`
recursive?: boolean;
}FileInfo#
Information supplied to directory-entry filters.
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.
declare class FileRef {}Constructor#
new FileRef()#
Creates a reference without accessing the filesystem.
constructor(path: Path)Static methods#
FileRef.is()#
Checks whether a value carries the compatible FileRef brand.
static is(x: unknown): x is FileRefInstance properties#
file.path#
The normalized native filesystem path.
get path(): stringfile.name#
The final path component including its extension.
get name(): stringfile.base#
The final path component without its last extension.
get base(): stringfile.extension#
The last filename extension including its leading dot.
get extension(): stringfile.fullExtension#
All filename extensions beginning at the first dot.
get fullExtension(): stringfile.directory#
A reference to the parent directory.
get directory(): FileReffile.core#
The final path component without any extension.
get core(): stringInstance methods#
file.join()#
Joins path segments to this reference.
file.webpath()#
Converts native separators to forward slashes.
webpath(): stringfile.append()#
Appends text directly to the path.
append(suffix: string): FileReffile.bare()#
Removes the final extension and optionally appends text.
bare(append?: string): FileReffile.debase()#
Removes a base path and optional suffix from this path.
file.text()#
Reads the file as UTF-8 text.
text(): Promise<string>file.json()#
Reads and parses the file as JSON.
json<T extends JSONValue>(): Promise<T>file.bytes()#
Reads the file as bytes.
bytes(): Promise<Uint8Array>file.arrayBuffer()#
Reads the file into an array buffer.
arrayBuffer(): Promise<ArrayBuffer>file.stream()#
Opens a readable byte stream for the file.
Pass the result to
stream.stringify() to decode UTF-8 text.
stream(): ReadableStream<Uint8Array>file.size()#
Returns the file size in bytes.
size(): Promise<number>file.write()#
Writes supported text, binary, blob, response, or stream input.
write(input: WritableInput): Promise<void>file.writeJSON()#
Writes a value as indented JSON.
writeJSON(input: JSONValue): Promise<void>file.exists()#
Checks whether the referenced path exists.
exists(): Promise<boolean>file.type()#
Returns the entry type, or null when the path is missing.
type(): Promise<FileType>file.modified()#
Returns the modification time as Unix milliseconds.
modified(): Promise<number>file.empty()#
Checks whether a file has zero bytes or a directory has no entries.
empty(): Promise<boolean>file.list()#
Lists immediate or recursive directory entries.
list(options?: ListOptions): Promise<FileRef[]>file.files()#
Lists only file entries.
files(options?: ListOptions): Promise<FileRef[]>file.dirs()#
Lists only directory entries.
dirs(options?: ListOptions): Promise<FileRef[]>file.create()#
Creates this directory.
Default: options.recursive is true.
create(options?: DirectoryOptions): Promise<void>file.remove()#
Removes this path.
Default: Missing paths do not fail unless options.fail is true.
remove(options?: RemoveOptions): Promise<void>file.copy()#
Copies this file or directory to another reference.
file.hash()#
Hashes the file contents.
Parameters
algorithm— A Web Crypto digest algorithm.
Default: "SHA-256"
hash(algorithm?: string): Promise<string>file.import()#
Dynamically imports the file, optionally returning one named export.
import(name?: string): Promise<any>file.discover()#
Walks upward to find a directory containing a filename.
discover(filename: string): Promise<FileRef>file.sibling()#
Returns a named reference in the same directory.
sibling(name: string): FileReffile.or()#
Returns this reference when it exists, otherwise a fallback value.
or<T>(fallback: () => T): Promise<this | T>file.toString()#
Returns the normalized path.
toString(): stringProtocol members#
file[Symbol.replace]()#
Replaces this reference's string value inside another string.
[Symbol.replace](
string: string,
replacement: string | StringReplacer,
): stringfile[symbol.stream]()#
Returns the file's stream through
@rcompat/symbol.stream.
[symbol.stream](): ReadableStream<Uint8Array>file[util.inspect.custom]()#
Formats the reference for Node-compatible object inspection.
[util.inspect.custom](): stringfile.Name protocol property#
The stable class name used by rcompat protocols.
get Name(): "FileRef"FileType#
The recognized kind of a filesystem entry, or null when it is missing.
type FileType = "directory" | "file" | "link" | null;Filter#
Selects directory entries synchronously or asynchronously.
Parameters
info— Information about the candidate entry.
type Filter = (info: FileInfo) => MaybePromise<boolean>;ListOptions#
Options for listing directory entries.
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.
type NamedStreamable<T = unknown> = Streamable<T> & { name: string };Path#
A filesystem path represented by a string or an existing reference.
type Path = string | FileRef;RemoveOptions#
Options for removing a filesystem entry.
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.
type Streamable<T = unknown> =
| Blob
| ReadableStream<T>
| { [symbol.stream](): ReadableStream<T> }
;WritableInput#
Content accepted by filesystem write operations.
type WritableInput =
| ArrayBuffer
| Uint8Array
| Blob
| ReadableStream
| Response
| string
;