maligator:fs
On this page
Read, write, and stream files, work with directories, and watch for changes.
Import from maligator:fs. This API is experimental. Load declarations as described in Use TypeScript.
Relative paths resolve against the working directory when an operation runs. Child paths and listing patterns use / and resolve below their directory handle. Directory listings order results by the code points of their relative paths and do not descend through symbolic links.
DiskFile.stream() gives you a ReadableStream of fresh byte chunks. It opens on the first pull and closes on EOF or cancellation. Byte offsets are inclusive. DiskFile.writer() queues writes, flushes and close on one descriptor. flush() uses fsync. Closing an unopened writer creates the file or truncates it unless append is enabled.
watch() starts on the iterator's first next(). It reports changes to a file or to the children of a directory. Enable recursive for subdirectories. Event paths include the watched path. Breaking from the loop closes the watcher. An abort closes the watcher and rejects with the signal's reason.
Failed filesystem operations reject with a FileSystemError. See Read and write files for walkthroughs.
file
A handle for the file at path. It does no I/O, so the file need not exist yet. Throws a TypeError for an empty path, a path with a null byte or a URL that is not a file: URL.
export const file: (path: FilePath) => DiskFile;import { file } from "maligator:fs";
const settings = file("settings.json");
if (await settings.exists()) console.log(await settings.json());
await file("out/report.txt").write("done\n", { atomic: true, createDirectories: true });import { file } from "maligator:fs";
await using output = file("copy.bin").writer();
for await (const chunk of file("input.bin").stream()) await output.write(chunk);directory
A handle for the directory at path. It does no I/O, so the directory need not exist yet. Throws a TypeError for an empty path, a path with a null byte or a URL that is not a file: URL.
export const directory: (path: FilePath) => DiskDirectory;Types: FilePath, DiskDirectory
import { directory } from "maligator:fs";
const reports = directory("out/reports");
await reports.create({ recursive: true });
await reports.file("latest.txt").write("done\n");
for (const report of await reports.files({ include: ["*.txt"] })) console.log(report.path);watch
Watch a file or directory using an async iterator. The first next() starts the watch. Breaking out of the loop, calling return(), or aborting the signal closes it.
export const watch: (path: FilePath, options?: WatchOptions) => AsyncIterableIterator<FileChange>;Types: FilePath, WatchOptions, FileChange
import { watch } from "maligator:fs";
for await (const change of watch("inbox", { recursive: true })) {
console.log(change.kind, change.path);
if (change.kind === "create") break;
}FileSystemError
The class of every rejection a failed filesystem operation causes.
export const FileSystemError: {
new (message: string, options: { code: string; syscall: string; path: string; destination?: string }): FileSystemError;
readonly prototype: FileSystemError;
};import { file, FileSystemError } from "maligator:fs";
try {
console.log(await file("notes.txt").text());
} catch (error) {
if (!(error instanceof FileSystemError) || error.code !== "ENOENT") throw error;
console.log("no notes yet");
}FilePath
A path, or a file: URL. A relative path resolves against the working directory when an operation runs.
type FilePath = string | URL;FileData
Contents to write. Strings are written as UTF-8; views write the bytes they cover.
type FileData = string | ArrayBufferView | ArrayBuffer;WriteOptions
How write stores the contents.
Full TypeScript declaration
type WriteOptions = {
/** Write a temporary file next to the target and rename it over the target, so readers see the old or the new contents and never a partial file. Defaults to false. */
atomic?: boolean;
/** Create missing parent directories first. Defaults to false. */
createDirectories?: boolean;
/** Permission bits for a created file, before the umask. Defaults to 0o666; an atomic write keeps the bits of the file it replaces. */
mode?: number;
};WriteOptions.atomic
Write a temporary file next to the target and rename it over the target, so readers see the old or the new contents and never a partial file. Defaults to false.
atomic?: boolean;WriteOptions.createDirectories
Create missing parent directories first. Defaults to false.
createDirectories?: boolean;WriteOptions.mode
Permission bits for a created file, before the umask. Defaults to 0o666; an atomic write keeps the bits of the file it replaces.
mode?: number;AppendOptions
How append creates a missing file.
Full TypeScript declaration
type AppendOptions = {
/** Create missing parent directories first. Defaults to false. */
createDirectories?: boolean;
/** Permission bits for a created file, before the umask. Defaults to 0o666. */
mode?: number;
};AppendOptions.createDirectories
Create missing parent directories first. Defaults to false.
createDirectories?: boolean;AppendOptions.mode
Permission bits for a created file, before the umask. Defaults to 0o666.
mode?: number;FileStreamOptions
Byte range and read size for DiskFile.stream().
Full TypeScript declaration
type FileStreamOptions = {
/** First byte to read, inclusive. Defaults to 0. */
start?: number;
/** Last byte to read, inclusive. Defaults to the end of the file. */
end?: number;
/** Maximum bytes per chunk. Defaults to 64 KiB. */
chunkSize?: number;
};FileStreamOptions.start
First byte to read, inclusive. Defaults to 0.
start?: number;FileStreamOptions.end
Last byte to read, inclusive. Defaults to the end of the file.
end?: number;FileStreamOptions.chunkSize
Maximum bytes per chunk. Defaults to 64 KiB.
chunkSize?: number;FileWriterOptions
How DiskFile.writer() opens its file.
Full TypeScript declaration
type FileWriterOptions = AppendOptions & {
/** Append to the existing file. Defaults to false, which truncates it when opened. */
append?: boolean;
};Types: AppendOptions
FileWriterOptions.append
Append to the existing file. Defaults to false, which truncates it when opened.
append?: boolean;FileWriter
A sink that opens the file on its first operation and queues operations in call order. Await a write before reusing its input buffer.
Full TypeScript declaration
interface FileWriter {
/** Write a chunk and fulfill with the number of bytes written. */
write(data: FileData): Promise<number>;
/** Flush preceding writes to the filesystem with fsync. */
flush(): Promise<void>;
/** Close after preceding operations. Repeated calls share the same result. */
close(): Promise<void>;
/** Close after preceding operations. */
end(): Promise<void>;
[Symbol.asyncDispose](): Promise<void>;
}Types: FileData
FileWriter.write
Write a chunk and fulfill with the number of bytes written.
write(data: FileData): Promise<number>;Types: FileData
FileWriter.flush
Flush preceding writes to the filesystem with fsync.
flush(): Promise<void>;FileWriter.close
Close after preceding operations. Repeated calls share the same result.
close(): Promise<void>;FileWriter.end
Close after preceding operations.
end(): Promise<void>;FileWriter.[Symbol.asyncDispose]
[Symbol.asyncDispose](): Promise<void>;WatchOptions
How watch() observes changes.
Full TypeScript declaration
type WatchOptions = {
/** Also watch subdirectories. Defaults to false. */
recursive?: boolean;
/** Reject with the signal's reason and close the watcher when it aborts. */
signal?: AbortSignal;
};WatchOptions.recursive
Also watch subdirectories. Defaults to false.
recursive?: boolean;WatchOptions.signal
Reject with the signal's reason and close the watcher when it aborts.
signal?: AbortSignal;FileChange
A filesystem notification. The OS can coalesce changes and may report a move as creation or deletion.
Full TypeScript declaration
type FileChange = {
/** The change reported by the filesystem. */
kind: "create" | "modify" | "delete" | "rename";
/** The changed path, including the watched path for a child. */
path: string;
};FileChange.kind
The change reported by the filesystem.
kind: "create" | "modify" | "delete" | "rename";FileChange.path
The changed path, including the watched path for a child.
path: string;TransferOptions
How copyTo and moveTo treat an existing destination.
Full TypeScript declaration
type TransferOptions = {
/** Replace an existing destination. Defaults to false, which rejects with `EEXIST`. */
overwrite?: boolean;
};TransferOptions.overwrite
Replace an existing destination. Defaults to false, which rejects with EEXIST.
overwrite?: boolean;StatOptions
Which entry stat describes.
Full TypeScript declaration
type StatOptions = {
/** Describe the target of a symbolic link instead of the link. Defaults to true. */
followSymlinks?: boolean;
};StatOptions.followSymlinks
Describe the target of a symbolic link instead of the link. Defaults to true.
followSymlinks?: boolean;FileStat
Metadata of a filesystem entry.
Full TypeScript declaration
type FileStat = {
/** The size in bytes. */
readonly size: number;
/** The last modification time. */
readonly mtime: Date;
readonly isFile: boolean;
readonly isDirectory: boolean;
/** True only when `followSymlinks` is false and the path is a link. */
readonly isSymbolicLink: boolean;
/** The file type and permission bits, as `st_mode` reports them. */
readonly mode: number;
};FileStat.size
The size in bytes.
readonly size: number;FileStat.mtime
The last modification time.
readonly mtime: Date;FileStat.isFile
readonly isFile: boolean;FileStat.isDirectory
readonly isDirectory: boolean;FileStat.isSymbolicLink
True only when followSymlinks is false and the path is a link.
readonly isSymbolicLink: boolean;FileStat.mode
The file type and permission bits, as st_mode reports them.
readonly mode: number;DiskFile
A file on disk. Creating a handle does no I/O; each method reads or changes the file when called. Failed operations reject with a FileSystemError.
Full TypeScript declaration
interface DiskFile {
/** The path as given, or the path of a `file:` URL. */
readonly path: string;
/** The media type implied by the file extension; text types carry `charset=utf-8`. */
readonly type: string;
/** Whether the path resolves, following symbolic links. Never rejects. */
exists(): Promise<boolean>;
/** Metadata of the entry; rejects when it is missing. */
stat(options?: StatOptions): Promise<FileStat>;
/** The contents as a Uint8Array over a fresh ArrayBuffer. */
bytes(): Promise<Uint8Array<ArrayBuffer>>;
/** The contents decoded as UTF-8, without a byte order mark. */
text(): Promise<string>;
/** The contents parsed as JSON. */
json(): Promise<unknown>;
/** Read a range incrementally. Cancellation closes the file. */
stream(options?: FileStreamOptions): ReadableStream<Uint8Array<ArrayBuffer>>;
/** Open a sink for incremental writes. */
writer(options?: FileWriterOptions): FileWriter;
/** Replace the contents, creating the file when it is missing. Fulfills with the number of bytes written. */
write(data: FileData, options?: WriteOptions): Promise<number>;
/** Add to the end of the file, creating it when it is missing. Fulfills with the number of bytes written. */
append(data: FileData, options?: AppendOptions): Promise<number>;
/** Remove the file; rejects when it is missing or a directory. */
delete(): Promise<void>;
/** Copy the contents and permission bits to another path. */
copyTo(destination: FilePath | DiskFile, options?: TransferOptions): Promise<void>;
/** Rename the file, copying across file systems. This handle keeps naming the old path. */
moveTo(destination: FilePath | DiskFile, options?: TransferOptions): Promise<void>;
}Types: FilePath, FileData, WriteOptions, AppendOptions, FileStreamOptions, FileWriterOptions, FileWriter, TransferOptions, StatOptions, FileStat
DiskFile.path
The path as given, or the path of a file: URL.
readonly path: string;DiskFile.type
The media type implied by the file extension; text types carry charset=utf-8.
readonly type: string;DiskFile.exists
Whether the path resolves, following symbolic links. Never rejects.
exists(): Promise<boolean>;DiskFile.stat
Metadata of the entry; rejects when it is missing.
stat(options?: StatOptions): Promise<FileStat>;Types: StatOptions, FileStat
DiskFile.bytes
The contents as a Uint8Array over a fresh ArrayBuffer.
bytes(): Promise<Uint8Array<ArrayBuffer>>;DiskFile.text
The contents decoded as UTF-8, without a byte order mark.
text(): Promise<string>;DiskFile.json
The contents parsed as JSON.
json(): Promise<unknown>;DiskFile.stream
Read a range incrementally. Cancellation closes the file.
stream(options?: FileStreamOptions): ReadableStream<Uint8Array<ArrayBuffer>>;Types: FileStreamOptions
DiskFile.writer
Open a sink for incremental writes.
writer(options?: FileWriterOptions): FileWriter;Types: FileWriterOptions, FileWriter
DiskFile.write
Replace the contents, creating the file when it is missing. Fulfills with the number of bytes written.
write(data: FileData, options?: WriteOptions): Promise<number>;Types: FileData, WriteOptions
DiskFile.append
Add to the end of the file, creating it when it is missing. Fulfills with the number of bytes written.
append(data: FileData, options?: AppendOptions): Promise<number>;Types: FileData, AppendOptions
DiskFile.delete
Remove the file; rejects when it is missing or a directory.
delete(): Promise<void>;DiskFile.copyTo
Copy the contents and permission bits to another path.
copyTo(destination: FilePath | DiskFile, options?: TransferOptions): Promise<void>;Types: FilePath, TransferOptions, DiskFile
DiskFile.moveTo
Rename the file, copying across file systems. This handle keeps naming the old path.
moveTo(destination: FilePath | DiskFile, options?: TransferOptions): Promise<void>;Types: FilePath, TransferOptions, DiskFile
DirectoryListOptions
Which entries to list. Patterns use *, ? and whole-segment ** on slash-separated paths relative to the directory. A pattern can match zero entries.
Full TypeScript declaration
type DirectoryListOptions = {
/** Include paths that match any of these patterns. Defaults to `['**']`. */
include?: ReadonlyArray<string>;
/** Leave out paths that match any of these patterns, even when included. */
exclude?: ReadonlyArray<string>;
/** Let wildcards match segments starting with a dot. Defaults to false. */
dot?: boolean;
/** Visit subdirectories. Defaults to true for `files()` and false for `entries()`. */
recursive?: boolean;
};DirectoryListOptions.include
Include paths that match any of these patterns. Defaults to ['**'].
include?: ReadonlyArray<string>;DirectoryListOptions.exclude
Leave out paths that match any of these patterns, even when included.
exclude?: ReadonlyArray<string>;DirectoryListOptions.dot
Let wildcards match segments starting with a dot. Defaults to false.
dot?: boolean;DirectoryListOptions.recursive
Visit subdirectories. Defaults to true for files() and false for entries().
recursive?: boolean;DirectoryEntry
An entry returned by DiskDirectory.entries().
Full TypeScript declaration
type DirectoryEntry = {
/** The final component of the entry's path. */
name: string;
/** A slash-separated path relative to the listed directory. */
path: string;
/** The entry's own kind. */
kind: "file" | "directory" | "symlink" | "other";
};DirectoryEntry.name
The final component of the entry's path.
name: string;DirectoryEntry.path
A slash-separated path relative to the listed directory.
path: string;DirectoryEntry.kind
The entry's own kind.
kind: "file" | "directory" | "symlink" | "other";CreateDirectoryOptions
How DiskDirectory.create() creates a directory.
Full TypeScript declaration
type CreateDirectoryOptions = {
/** Create missing parents and succeed if the directory already exists. Defaults to false. */
recursive?: boolean;
/** Permission bits for created directories before the umask. Defaults to 0o777. */
mode?: number;
};CreateDirectoryOptions.recursive
Create missing parents and succeed if the directory already exists. Defaults to false.
recursive?: boolean;CreateDirectoryOptions.mode
Permission bits for created directories before the umask. Defaults to 0o777.
mode?: number;DeleteDirectoryOptions
How DiskDirectory.delete() removes a directory.
Full TypeScript declaration
type DeleteDirectoryOptions = {
/** Remove the directory and its contents. Defaults to false. */
recursive?: boolean;
};DeleteDirectoryOptions.recursive
Remove the directory and its contents. Defaults to false.
recursive?: boolean;DiskDirectory
A directory on disk. Creating a handle does no I/O. Directory walks report symbolic links as entries and skip descending into them.
Full TypeScript declaration
interface DiskDirectory {
/** The path as given, or the path of a `file:` URL. */
readonly path: string;
/** Whether the path resolves, following symbolic links. */
exists(): Promise<boolean>;
/** Metadata of the entry at `path`. */
stat(options?: StatOptions): Promise<FileStat>;
/** A lazy file handle at a slash-separated path below the directory. */
file(relative: string): DiskFile;
/** A lazy directory handle at a slash-separated path below the directory. */
directory(relative: string): DiskDirectory;
/** A handle if the named entry is a regular file, or undefined if absent or another kind. */
get(relative: string): Promise<DiskFile | undefined>;
/** Regular files ordered by the code points of their relative paths. Visits subdirectories by default. */
files(options?: DirectoryListOptions): Promise<Array<DiskFile>>;
/** Entries ordered by the code points of their relative paths. Lists direct children by default. */
entries(options?: DirectoryListOptions): Promise<Array<DirectoryEntry>>;
/** Create the directory. A non-recursive create rejects if the path already exists. */
create(options?: CreateDirectoryOptions): Promise<void>;
/** Remove the directory. A non-recursive delete requires an empty directory. */
delete(options?: DeleteDirectoryOptions): Promise<void>;
}Types: StatOptions, FileStat, DiskFile, DirectoryListOptions, DirectoryEntry, CreateDirectoryOptions, DeleteDirectoryOptions
DiskDirectory.path
The path as given, or the path of a file: URL.
readonly path: string;DiskDirectory.exists
Whether the path resolves, following symbolic links.
exists(): Promise<boolean>;DiskDirectory.stat
Metadata of the entry at path.
stat(options?: StatOptions): Promise<FileStat>;Types: StatOptions, FileStat
DiskDirectory.file
A lazy file handle at a slash-separated path below the directory.
file(relative: string): DiskFile;Types: DiskFile
DiskDirectory.directory
A lazy directory handle at a slash-separated path below the directory.
directory(relative: string): DiskDirectory;Types: DiskDirectory
DiskDirectory.get
A handle if the named entry is a regular file, or undefined if absent or another kind.
get(relative: string): Promise<DiskFile | undefined>;Types: DiskFile
DiskDirectory.files
Regular files ordered by the code points of their relative paths. Visits subdirectories by default.
files(options?: DirectoryListOptions): Promise<Array<DiskFile>>;Types: DiskFile, DirectoryListOptions
DiskDirectory.entries
Entries ordered by the code points of their relative paths. Lists direct children by default.
entries(options?: DirectoryListOptions): Promise<Array<DirectoryEntry>>;Types: DirectoryListOptions, DirectoryEntry
DiskDirectory.create
Create the directory. A non-recursive create rejects if the path already exists.
create(options?: CreateDirectoryOptions): Promise<void>;Types: CreateDirectoryOptions
DiskDirectory.delete
Remove the directory. A non-recursive delete requires an empty directory.
delete(options?: DeleteDirectoryOptions): Promise<void>;Types: DeleteDirectoryOptions
FileSystemError instance
A failed filesystem operation. The message reads like Node's: the code, a description, the system call and the paths.
Full TypeScript declaration
interface FileSystemError extends Error {
/** The error name, such as `ENOENT` or `EACCES`. */
readonly code: string;
/** The system call that failed, such as `open` or `rename`. */
readonly syscall: string;
/** The path the call failed on. */
readonly path: string;
/** The destination of a failed copy or move. */
readonly destination?: string;
}FileSystemError.code
The error name, such as ENOENT or EACCES.
readonly code: string;FileSystemError.syscall
The system call that failed, such as open or rename.
readonly syscall: string;FileSystemError.path
The path the call failed on.
readonly path: string;FileSystemError.destination
The destination of a failed copy or move.
readonly destination?: string;