API Reference

Complete API documentation for @visulima/fs.

Last updated:

API Reference

Complete API documentation for @visulima/fs.

Imports

// Main module
import {
    readJson,
    readJsonSync,
    writeJson,
    writeJsonSync,
    walk,
    walkSync,
    findUp,
    findUpSync,
    ensureDir,
    ensureDirSync,
    ensureFile,
    ensureFileSync,
    ensureLink,
    ensureLinkSync,
    ensureSymlink,
    ensureSymlinkSync,
    emptyDir,
    emptyDirSync,
    glob,
    globSync,
    isGlob,
    globParent,
    match,
    matcher,
} from "@visulima/fs";

// YAML (requires 'yaml' peer dependency)
import { readYaml, readYamlSync, writeYaml, writeYamlSync } from "@visulima/fs/yaml";

// Size utilities
import { getFileSize, getFileSizeSync, getCompressedSize, getCompressedSizeSync } from "@visulima/fs/size";

// EOL utilities
import { detectEOL, detectEOLSync, normalizeEOL, normalizeEOLSync } from "@visulima/fs/eol";

// Glob helpers (each is also available as a dedicated subpath for tree-shaking)
import { glob, globSync } from "@visulima/fs/glob";
import isGlob from "@visulima/fs/is-glob";
import globParent from "@visulima/fs/glob-parent";
import { match, matcher } from "@visulima/fs/match";

JSON Functions

readJson(path: string): Promise<any>

Read and parse a JSON file.

Parameters:

  • path (string): Path to JSON file

Returns: Promise resolving to parsed JSON data

Example:

const config = await readJson("config.json");

readJsonSync(path: string): any

Synchronously read and parse a JSON file.

Parameters:

  • path (string): Path to JSON file

Returns: Parsed JSON data

Example:

const packageJson = readJsonSync("package.json");

writeJson(path: string, data: any, options?: WriteJsonOptions): Promise<void>

Write data to a JSON file with formatting.

Parameters:

  • path (string): Output file path
  • data (any): Data to write
  • options (WriteJsonOptions, optional): Formatting options
    • spaces (number): Indentation spaces (default: 2)

Returns: Promise that resolves when complete

Example:

await writeJson("output.json", { key: "value" }, { spaces: 2 });

writeJsonSync(path: string, data: any, options?: WriteJsonOptions): void

Synchronously write data to a JSON file.

Parameters:

  • path (string): Output file path
  • data (any): Data to write
  • options (WriteJsonOptions, optional): Formatting options

Example:

writeJsonSync("data.json", { items: [1, 2, 3] });

YAML Functions

readYaml(path: string): Promise<any>

Read and parse a YAML file.

Requires: yaml peer dependency

Parameters:

  • path (string): Path to YAML file

Returns: Promise resolving to parsed YAML data

Example:

const config = await readYaml("config.yml");

readYamlSync(path: string): any

Synchronously read and parse a YAML file.

Parameters:

  • path (string): Path to YAML file

Returns: Parsed YAML data

Example:

const data = readYamlSync("data.yaml");

writeYaml(path: string, data: any): Promise<void>

Write data to a YAML file.

Parameters:

  • path (string): Output file path
  • data (any): Data to write

Returns: Promise that resolves when complete

Example:

await writeYaml("output.yml", { name: "project" });

writeYamlSync(path: string, data: any): void

Synchronously write data to a YAML file.

Parameters:

  • path (string): Output file path
  • data (any): Data to write

Example:

writeYamlSync("config.yaml", configuration);

Directory Walking

walk(path: string, options?: WalkOptions): AsyncIterableIterator<WalkEntry>

Recursively walk a directory tree.

Parameters:

  • path (string): Directory to walk
  • options (WalkOptions, optional):
    • maxDepth (number): Maximum depth (default: Infinity)
    • includeFiles (boolean): Include files (default: true)
    • includeDirs (boolean): Include directories (default: true)
    • includeSymlinks (boolean): Include symlinks (default: true)
    • followSymlinks (boolean): Follow symlinks (default: false)
    • extensions (string[]): Filter by extensions
    • match (string[] | RegExp[]): Include patterns
    • skip (string[] | RegExp[]): Exclude patterns

Returns: Async iterable of WalkEntry objects

WalkEntry Type:

interface WalkEntry {
    path: string;
    isFile: boolean;
    isDirectory: boolean;
    isSymlink: boolean;
}

Example:

for await (const entry of walk("src", {
    extensions: [".ts", ".tsx"],
    skip: ["**/*.test.ts"],
})) {
    console.log(entry.path);
}

walkSync(path: string, options?: WalkOptions): IterableIterator<WalkEntry>

Synchronously walk a directory tree.

Parameters:

  • Same as walk()

Returns: Iterable of WalkEntry objects

Example:

for (const entry of walkSync("src")) {
    console.log(entry.path);
}

Finding Files

findUp(matcher: string | string[] | FindUpMatcher, options?: FindUpOptions): Promise<string | undefined>

Find a file or directory by walking up parent directories.

Parameters:

  • matcher (string | string[] | Function):
    • String: Filename to find
    • Array: Multiple possible filenames
    • Function: Custom matcher (dir: string, file: string) => boolean | Promise<boolean>
  • options (FindUpOptions, optional):
    • cwd (string): Starting directory (default: process.cwd())
    • stopAt (string): Stop searching at this directory
    • type (string): 'file' or 'directory'

Returns: Promise resolving to found path or undefined

Example:

// Find by name
const pkg = await findUp("package.json");

// Multiple names
const config = await findUp([".config.json", "config.json"]);

// Custom matcher
const found = await findUp((dir, file) => {
    return file === "package.json";
});

findUpSync(matcher: string | string[] | FindUpMatcher, options?: FindUpOptions): string | undefined

Synchronously find a file or directory.

Parameters:

  • Same as findUp()

Returns: Found path or undefined

Example:

const gitRoot = findUpSync(".git", { type: "directory" });

Ensuring Files and Directories

ensureDir(path: string): Promise<string>

Ensure directory exists, create if necessary.

Parameters:

  • path (string): Directory path

Returns: Promise resolving to directory path

Example:

await ensureDir("src/components/ui");

ensureDirSync(path: string): string

Synchronously ensure directory exists.

Parameters:

  • path (string): Directory path

Returns: Directory path

Example:

ensureDirSync("dist/assets");

ensureFile(path: string): Promise<void>

Ensure file exists, create if necessary.

Parameters:

  • path (string): File path

Returns: Promise that resolves when complete

Example:

await ensureFile("logs/app.log");

ensureFileSync(path: string): void

Synchronously ensure file exists.

Parameters:

  • path (string): File path

Example:

ensureFileSync("cache/data.txt");

ensureLink(srcPath: string, destPath: string): Promise<void>

Ensure hard link exists.

Parameters:

  • srcPath (string): Source file path
  • destPath (string): Destination link path

Returns: Promise that resolves when complete

Example:

await ensureLink("source.txt", "link.txt");

ensureLinkSync(srcPath: string, destPath: string): void

Synchronously ensure hard link exists.

Parameters:

  • srcPath (string): Source file path
  • destPath (string): Destination link path

Example:

ensureLinkSync("original.dat", "link.dat");

ensureSymlink(target: string, path: string, type?: "file" | "dir"): Promise<void>

Ensure symbolic link exists.

Parameters:

  • target (string): Target path
  • path (string): Symlink path
  • type (string, optional): 'file' or 'dir'

Returns: Promise that resolves when complete

Example:

await ensureSymlink("target/file.txt", "link.txt", "file");
await ensureSymlink("target/directory", "link-dir", "dir");

ensureSymlinkSync(target: string, path: string, type?: "file" | "dir"): void

Synchronously ensure symbolic link exists.

Parameters:

  • Same as ensureSymlink()

Example:

ensureSymlinkSync("source.txt", "link.txt", "file");

Directory Utilities

emptyDir(path: string): Promise<boolean>

Check if directory is empty.

Parameters:

  • path (string): Directory path

Returns: Promise resolving to true if empty or doesn't exist

Example:

const isEmpty = await emptyDir("temp");

emptyDirSync(path: string): boolean

Synchronously check if directory is empty.

Parameters:

  • path (string): Directory path

Returns: True if empty or doesn't exist

Example:

if (emptyDirSync("cache")) {
    console.log("Cache is empty");
}

Size Functions

getFileSize(path: string): Promise<number>

Get file size in bytes.

Parameters:

  • path (string): File path

Returns: Promise resolving to size in bytes

Example:

const bytes = await getFileSize("large-file.json");
console.log(`${bytes} bytes`);

getFileSizeSync(path: string): number

Synchronously get file size.

Parameters:

  • path (string): File path

Returns: Size in bytes

Example:

const size = getFileSizeSync("image.png");

getCompressedSize(path: string, compression: "gzip" | "brotli"): Promise<number>

Get compressed file size.

Parameters:

  • path (string): File path
  • compression (string): Compression type ('gzip' or 'brotli')

Returns: Promise resolving to compressed size in bytes

Example:

const gzipSize = await getCompressedSize("bundle.js", "gzip");
const brotliSize = await getCompressedSize("bundle.js", "brotli");

getCompressedSizeSync(path: string, compression: "gzip" | "brotli"): number

Synchronously get compressed file size.

Parameters:

  • Same as getCompressedSize()

Returns: Compressed size in bytes

Example:

const size = getCompressedSizeSync("file.txt", "gzip");

EOL Functions

detectEOL(path: string): Promise<string>

Detect line ending style in a file.

Parameters:

  • path (string): File path

Returns: Promise resolving to EOL character(s): '\n', '\r\n', or '\r'

Example:

const eol = await detectEOL("source.txt");
if (eol === "\r\n") {
    console.log("Windows line endings");
}

detectEOLSync(path: string): string

Synchronously detect line ending style.

Parameters:

  • path (string): File path

Returns: EOL character(s)

Example:

const lineEnding = detectEOLSync("file.txt");

normalizeEOL(path: string, eol: string): Promise<void>

Normalize line endings in a file.

Parameters:

  • path (string): File path
  • eol (string): Target EOL ('\n' or '\r\n')

Returns: Promise that resolves when complete

Example:

await normalizeEOL("source.txt", "\n"); // Convert to Unix
await normalizeEOL("source.txt", "\r\n"); // Convert to Windows

normalizeEOLSync(path: string, eol: string): void

Synchronously normalize line endings.

Parameters:

  • path (string): File path
  • eol (string): Target EOL

Example:

normalizeEOLSync("file.txt", "\n");

Glob Matching

File matching helpers built on tinyglobby, is-glob, glob-parent and picomatch. All four libraries are bundled into the built output, so @visulima/fs has no extra runtime dependencies for glob support. tinyglobby and picomatch ship with a small local patch that enables negated ignore patterns (see glob).

Attribution: portions of this section (in particular the glob/globSync signatures and the options table) are adapted from the tinyglobby documentation, © 2024 Madeline Gurriarán, distributed under the MIT License. is-glob © 2014–present Jon Schlinkert, glob-parent © 2015–present Gulp Team & contributors, picomatch © 2017–present Jon Schlinkert — all MIT.

glob(patterns: string | readonly string[], options?: GlobOptions): Promise<string[]>

Asynchronously match files following one or more glob patterns.

Pattern forms:

  • Plain globsrc/**/*.ts
  • Negated pattern!src/**/*.spec.ts inside patterns adds to the internal ignore list (same as passing it via ignore).
  • Negated ignore — a leading ! inside the ignore option un-ignores entries an earlier ignore pattern would drop, e.g. ignore: ["dist/**", "!dist/index.d.ts"].

Parameters:

  • patterns (string | readonly string[]): One or more glob patterns.
  • options (GlobOptions, optional): See Glob Options.

Returns: Promise resolving to the list of matched paths (relative to cwd unless absolute is true).

Example:

import { glob } from "@visulima/fs";

const scripts = await glob("src/**/*.{ts,js}", {
    cwd: process.cwd(),
    ignore: ["**/node_modules/**"],
});

// Negated ignore: drop the whole `dist/` tree except the type entry point.
const distPublic = await glob("**/*", {
    ignore: ["dist/**", "!dist/index.d.ts"],
});

globSync(patterns: string | readonly string[], options?: GlobOptions): string[]

Synchronous counterpart of glob. Supports the same pattern forms — including negated ignores.

Example:

import { globSync } from "@visulima/fs";

const tests = globSync(["**/*.test.ts", "!dist/**"]);

const keep = globSync("**/*.ts", {
    ignore: ["ignored/**", "!ignored/keep.ts"],
});

Glob Options

OptionTypeDefaultDescription
absolutebooleanfalseReturn absolute paths instead of paths relative to cwd.
braceExpansionbooleantrueEnable brace expansion syntax like {a,b} or {1..9}.
caseSensitiveMatchbooleantrueMatch in case-sensitive mode.
cwdstring | URLprocess.cwd()Working directory for the search.
debugbooleanfalseLog debug information (intended for development only; log format is not stable).
deepnumberInfinityMaximum directory depth to crawl.
dotbooleanfalseReturn dot-prefixed entries (e.g. .gitignore).
expandDirectoriesbooleantrueAuto-expand directory patterns. Disable when migrating from fast-glob.
extglobbooleantrueEnable extglobs like +(pattern).
followSymbolicLinksbooleantrueTraverse and include symbolic links. Can slightly affect performance.
fsPartial<FSLike>node:fsOverride node:fs functions (useful for virtual file systems).
globstarbooleantrueEnable ** to match nested directories. When false, ** behaves like *.
ignorestring | readonly string[][]Additional patterns to exclude from the results. Entries starting with ! un-ignore a path that an earlier pattern would drop, e.g. ignore: ["dist/**", "!dist/index.d.ts"].
onlyDirectoriesbooleanfalseReturn only directories. When true, onlyFiles is implicitly disabled.
onlyFilesbooleantrueReturn only files.
signalAbortSignalundefinedAbortSignal to stop crawling the file system.

isGlob(value: unknown, options?: IsGlobOptions): boolean

Returns true if the given value looks like a glob pattern (including extglobs like @(foo|bar)). Escaped meta characters such as \* are not considered globs. Non-string values always return false.

Parameters:

  • value (unknown): The value to inspect.
  • options (IsGlobOptions, optional):
    • strict (boolean): When false, matches more permissively — any string containing unescaped glob meta characters (*, ?, {}, (), []) is treated as a glob. Default: true.

Example:

import { isGlob } from "@visulima/fs";

isGlob("src/**/*.ts"); // true
isGlob("src/index.ts"); // false
isGlob("src/\\*.ts"); // false — escaped
isGlob("!foo.js"); // true — negation
isGlob("(abc)", { strict: false }); // true

globParent(pattern: string, options?: GlobParentOptions): string

Extracts the non-glob parent directory from a glob pattern. Useful when you need to know which directory to watch or walk for a given pattern.

Parameters:

  • pattern (string): The glob pattern to inspect.
  • options (GlobParentOptions, optional):
    • flipBackslashes (boolean): On Windows, flip backslashes to forward slashes before analysing. Default: true.

Example:

import { globParent } from "@visulima/fs";

globParent("src/**/*.ts"); // "src"
globParent("foo/{a,b}/*.js"); // "foo"
globParent("foo/bar.js"); // "foo"
globParent("index.ts"); // "."

match(value: string | string[], pattern: string | string[], options?: MatchOptions): boolean

Test whether a path (or any of a list of paths) matches one or more glob patterns. For repeated matches against the same pattern, prefer matcher to compile the pattern once.

Example:

import { match } from "@visulima/fs";

match("src/index.ts", "src/**/*.ts"); // true
match("src/index.ts", ["**/*.js", "**/*.ts"]); // true
match(["a.ts", "b.js"], "**/*.ts"); // true (any value matches)

matcher(pattern: string | string[], options?: MatchOptions): (value: string) => boolean

Compile a glob pattern into a reusable single-argument predicate. The returned function accepts exactly one argument, so it is safe to pass to Array.prototype.filter without triggering picomatch's returnObject parameter.

Example:

import { matcher } from "@visulima/fs";

const isTs = matcher("**/*.ts");
["a.ts", "b.js", "c.ts"].filter(isTs); // ["a.ts", "c.ts"]

const isScript = matcher(["**/*.ts", "**/*.js"]);
isScript("a.css"); // false

MatchOptions is re-exported unchanged from picomatch.PicomatchOptions — see the picomatch options reference for the full list.


TypeScript Types

// Walk entry
interface WalkEntry {
    path: string;
    isFile: boolean;
    isDirectory: boolean;
    isSymlink: boolean;
}

// Walk options
interface WalkOptions {
    maxDepth?: number;
    includeFiles?: boolean;
    includeDirs?: boolean;
    includeSymlinks?: boolean;
    followSymlinks?: boolean;
    extensions?: string[];
    match?: (string | RegExp)[];
    skip?: (string | RegExp)[];
}

// Find up options
interface FindUpOptions {
    cwd?: string;
    stopAt?: string;
    type?: "file" | "directory";
}

// Find up matcher
type FindUpMatcher = (directory: string, file: string) => boolean | Promise<boolean>;

// Write JSON options
interface WriteJsonOptions {
    spaces?: number;
}

// Glob options (adapted from tinyglobby)
interface GlobOptions {
    absolute?: boolean;
    braceExpansion?: boolean;
    caseSensitiveMatch?: boolean;
    cwd?: string | URL;
    debug?: boolean;
    deep?: number;
    dot?: boolean;
    expandDirectories?: boolean;
    extglob?: boolean;
    followSymbolicLinks?: boolean;
    fs?: Partial<import("fdir").FSLike>;
    globstar?: boolean;
    ignore?: string | readonly string[];
    onlyDirectories?: boolean;
    onlyFiles?: boolean;
    signal?: AbortSignal;
}

interface IsGlobOptions {
    strict?: boolean;
}

interface GlobParentOptions {
    flipBackslashes?: boolean;
}

// MatchOptions === picomatch.PicomatchOptions (re-exported as-is)

On this page

API ReferenceImportsJSON FunctionsreadJson(path: string): Promise<any>readJsonSync(path: string): anywriteJson(path: string, data: any, options?: WriteJsonOptions): Promise<void>writeJsonSync(path: string, data: any, options?: WriteJsonOptions): voidYAML FunctionsreadYaml(path: string): Promise<any>readYamlSync(path: string): anywriteYaml(path: string, data: any): Promise<void>writeYamlSync(path: string, data: any): voidDirectory Walkingwalk(path: string, options?: WalkOptions): AsyncIterableIterator<WalkEntry>walkSync(path: string, options?: WalkOptions): IterableIterator<WalkEntry>Finding FilesfindUp(matcher: string | string[] | FindUpMatcher, options?: FindUpOptions): Promise<string | undefined>findUpSync(matcher: string | string[] | FindUpMatcher, options?: FindUpOptions): string | undefinedEnsuring Files and DirectoriesensureDir(path: string): Promise<string>ensureDirSync(path: string): stringensureFile(path: string): Promise<void>ensureFileSync(path: string): voidensureLink(srcPath: string, destPath: string): Promise<void>ensureLinkSync(srcPath: string, destPath: string): voidensureSymlink(target: string, path: string, type?: "file" | "dir"): Promise<void>ensureSymlinkSync(target: string, path: string, type?: "file" | "dir"): voidDirectory UtilitiesemptyDir(path: string): Promise<boolean>emptyDirSync(path: string): booleanSize FunctionsgetFileSize(path: string): Promise<number>getFileSizeSync(path: string): numbergetCompressedSize(path: string, compression: "gzip" | "brotli"): Promise<number>getCompressedSizeSync(path: string, compression: "gzip" | "brotli"): numberEOL FunctionsdetectEOL(path: string): Promise<string>detectEOLSync(path: string): stringnormalizeEOL(path: string, eol: string): Promise<void>normalizeEOLSync(path: string, eol: string): voidGlob Matchingglob(patterns: string | readonly string[], options?: GlobOptions): Promise<string[]>globSync(patterns: string | readonly string[], options?: GlobOptions): string[]Glob OptionsisGlob(value: unknown, options?: IsGlobOptions): booleanglobParent(pattern: string, options?: GlobParentOptions): stringmatch(value: string | string[], pattern: string | string[], options?: MatchOptions): booleanmatcher(pattern: string | string[], options?: MatchOptions): (value: string) => booleanTypeScript Types
Support

Contribute to our work and keep us going

Community is the heart of open source. The success of our packages wouldn't be possible without the incredible contributions of users, testers, and developers who collaborate with us every day.Want to get involved? Here are some tips on how you can make a meaningful impact on our open source projects.

Ready to help us out?

Be sure to check out the package's contribution guidelines first. They'll walk you through the process on how to properly submit an issue or pull request to our repositories.

Submit a pull request

Found something to improve? Fork the repo, make your changes, and open a PR. We review every contribution and provide feedback to help you get merged.

Good first issues

Simple issues suited for people new to open source development, and often a good place to start working on a package.
View good first issues