Visulima fs
Human friendly file system utilities for Node.js
Daniel Bannert's open source work is supported by the community on GitHub Sponsors
Install
npm install @visulima/fs
yarn add @visulima/fs
pnpm add @visulima/fs
Usage
walk
import { walk } from "@visulima/fs";
const filesAndFolders: string[] = [];
for await (const index of walk(`${__dirname}/fixtures`, {})) {
filesAndFolders.push(index.path);
}
console.log(filesAndFolders);
walkSync
import { walkSync } from "@visulima/fs";
const filesAndFolders: string[] = [];
for (const index of walkSync(`${__dirname}/fixtures`, {})) {
filesAndFolders.push(index.path);
}
console.log(filesAndFolders);
API for walk
and walkSync
path
Type: string
The directory to start from.
options
Type: object
maxDepth
Type: number
Default: Infinity
Optional: true
Description: The maximum depth of the file tree to be walked recursively.
includeFiles
Type: boolean
Default: true
Optional: true
Description: Indicates whether file entries should be included or not.
includeDirs
Type: boolean
Default: true
Optional: true
Description: Indicates whether directory entries should be included or not.
includeSymlinks
Type: boolean
Default: true
Optional: true
Description: Indicates whether symlink entries should be included or not. This option is meaningful only if followSymlinks is set to false.
followSymlinks
Type: boolean
Default: false
Optional: true
Description: Indicates whether symlinks should be resolved or not.
extensions
Type: string[]
Default: undefined
Optional: true
Description: List of file extensions used to filter entries. If specified, entries without the file extension specified by this option are excluded.
match
Type: (RegExp | string)[]
Default: undefined
Optional: true
Description: List of regular expression or glob patterns used to filter entries. If specified, entries that do not match the patterns specified by this option are excluded.
skip
Type: (RegExp | string)[]
Default: undefined
Optional: true
Description: List of regular expression or glob patterns used to filter entries. If specified, entries matching the patterns specified by this option are excluded.
findUp
Find a file or directory by walking up parent directories.
import { findUp } from "@visulima/fs";
const file = await findUp("package.json");
console.log(file);
findUpSync
Find a file or directory by walking up parent directories.
import { findUpSync } from "@visulima/fs";
const file = findUpSync("package.json");
console.log(file);
API for findUp
and findUpSync
name
Type: string[] | string | ((directory: PathLike) => PathLike | Promise<PathLike | typeof FIND_UP_STOP> | typeof FIND_UP_STOP)
Sync Type: string[] | string | ((directory: PathLike) => PathLike | typeof FIND_UP_STOP)
The name of the file or directory to find.
If an array is specified, the first item that exists will be returned.
A function that will be called with each directory until it returns a string with the path, which stops the search, or the root directory has been reached and nothing was found. Useful if you want to match files with certain patterns, set of permissions, or other advanced use-cases.
When using async mode, the matcher may optionally be an async or promise-returning function that returns the path.
options
Type: object
cwd
Type: URL | string
Default: process.cwd()
The directory to start from.
type
Type: string
Default: 'file'
Values: 'file' | 'directory'
The type of path to match.
stopAt
Type: URL | string
Default: Root directory
A directory path where the search halts if no matches are found before reaching this point.
allowSymlinks
Type: boolean
Default: true
Allow symbolic links to match if they point to the target file or directory.
readFile
Read a file.
import { readFile } from "@visulima/fs";
const file = await readFile("package.json");
console.log(file);
readFileSync
Read a file.
import { readFileSync } from "@visulima/fs";
const file = readFileSync("package.json");
console.log(file);
API for readFile
and readFileSync
path
Type: string
The path to the file to read.
options
Type: object
buffer
Type: boolean
Default: true
Optional: true
Description: Indicates whether the file contents should be returned as a Buffer or a string.
compression
Type: "brotli" | "gzip" | undefined
Default: undefined
Optional: true
Description: The file compression.
encoding
Type: "ascii" | "base64" | "base64url" | "hex" | "latin1" | "ucs-2" | "ucs2" | "utf-8" | "utf-16le" | "utf8" | "utf16le" | undefined
Default: utf8
Optional: true
flag
Type: number | string | undefined
Default: 'r'
Optional: true
isAccessible
Check if a file or directory exists and is accessible.
import { isAccessible } from "@visulima/fs";
const file = await isAccessible("package.json");
console.log(file);
isAccessibleSync
Check if a file or directory exists and is accessible.
import { isAccessibleSync } from "@visulima/fs";
const file = isAccessibleSync("package.json");
console.log(file);
API for isAccessible
and isAccessibleSync
path
Type: string
The path to the file or directory to check.
mode
Type: number
Default: fs.constants.F_OK
Optional: true
Description: The accessibility mode.
Utilities
parseJson
Parse JSON with more helpful errors.
import { parseJson, JSONError } from "@visulima/fs/utils";
const json = '{\n\t"foo": true,\n}';
JSON.parse(json);
parseJson(json);
parseJson(json, "foo.json");
API for parseJson
json
Type: string
The JSON string to parse.
reviver
Type: Function
Prescribes how the value originally produced by parsing is transformed, before being returned. See JSON.parse docs for more.
filename
Type: string
The filename to use in error messages.
API for JSONError
Exposed for use in instanceof
checks.
fileName
Type: string
The filename displayed in the error message.
codeFrame
Type: string
The printable section of the JSON which produces the error.
Api Docs
error
Classes
AlreadyExistsError
Error thrown when file already exists.
Extends
Constructors
new AlreadyExistsError()
new AlreadyExistsError(message): AlreadyExistsError
Creates a new instance.
Parameters
• message: string
The error message.
Returns
AlreadyExistsError
Overrides
Error.constructor
Defined in
packages/fs/src/error/already-exists-error.ts:9
Accessors
code
get code(): string
set code(_name): void
Parameters
• _name: string
Returns
string
Defined in
packages/fs/src/error/already-exists-error.ts:14
name
get name(): string
set name(_name): void
Parameters
• _name: string
Returns
string
Overrides
Error.name
Defined in
packages/fs/src/error/already-exists-error.ts:24
Methods
captureStackTrace()
static captureStackTrace(targetObject, constructorOpt?): void
Create .stack property on a target object
Parameters
• targetObject: object
• constructorOpt?: Function
Returns
void
Inherited from
Error.captureStackTrace
Defined in
node_modules/.pnpm/@types+node@18.19.15/node_modules/@types/node/globals.d.ts:20
Properties
cause?
optional cause: unknown;
Inherited from
Error.cause
Defined in
node_modules/.pnpm/typescript@5.6.3/node_modules/typescript/lib/lib.es2022.error.d.ts:24
message
message: string;
Inherited from
Error.message
Defined in
node_modules/.pnpm/typescript@5.6.3/node_modules/typescript/lib/lib.es5.d.ts:1077
stack?
optional stack: string;
Inherited from
Error.stack
Defined in
node_modules/.pnpm/typescript@5.6.3/node_modules/typescript/lib/lib.es5.d.ts:1078
prepareStackTrace()?
static optional prepareStackTrace: (err, stackTraces) => any;
Optional override for formatting stack traces
Parameters
• err: Error
• stackTraces: CallSite
[]
Returns
any
See
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
Inherited from
Error.prepareStackTrace
Defined in
node_modules/.pnpm/@types+node@18.19.15/node_modules/@types/node/globals.d.ts:27
stackTraceLimit
static stackTraceLimit: number;
Inherited from
Error.stackTraceLimit
Defined in
node_modules/.pnpm/@types+node@18.19.15/node_modules/@types/node/globals.d.ts:29
DirectoryError
Error thrown when an operation is not allowed on a directory.
Extends
Constructors
new DirectoryError()
new DirectoryError(message): DirectoryError
Creates a new instance.
Parameters
• message: string
The error message.
Returns
DirectoryError
Overrides
Error.constructor
Defined in
packages/fs/src/error/directory-error.ts:9
Accessors
code
get code(): string
set code(_name): void
Parameters
• _name: string
Returns
string
Defined in
packages/fs/src/error/directory-error.ts:14
name
get name(): string
set name(_name): void
Parameters
• _name: string
Returns
string
Overrides
Error.name
Defined in
packages/fs/src/error/directory-error.ts:24
Methods
captureStackTrace()
static captureStackTrace(targetObject, constructorOpt?): void
Create .stack property on a target object
Parameters
• targetObject: object
• constructorOpt?: Function
Returns
void
Inherited from
Error.captureStackTrace
Defined in
node_modules/.pnpm/@types+node@18.19.15/node_modules/@types/node/globals.d.ts:20
Properties
cause?
optional cause: unknown;
Inherited from
Error.cause
Defined in
node_modules/.pnpm/typescript@5.6.3/node_modules/typescript/lib/lib.es2022.error.d.ts:24
message
message: string;
Inherited from
Error.message
Defined in
node_modules/.pnpm/typescript@5.6.3/node_modules/typescript/lib/lib.es5.d.ts:1077
stack?
optional stack: string;
Inherited from
Error.stack
Defined in
node_modules/.pnpm/typescript@5.6.3/node_modules/typescript/lib/lib.es5.d.ts:1078
prepareStackTrace()?
static optional prepareStackTrace: (err, stackTraces) => any;
Optional override for formatting stack traces
Parameters
• err: Error
• stackTraces: CallSite
[]
Returns
any
See
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
Inherited from
Error.prepareStackTrace
Defined in
node_modules/.pnpm/@types+node@18.19.15/node_modules/@types/node/globals.d.ts:27
stackTraceLimit
static stackTraceLimit: number;
Inherited from
Error.stackTraceLimit
Defined in
node_modules/.pnpm/@types+node@18.19.15/node_modules/@types/node/globals.d.ts:29
NotEmptyError
Error thrown when a directory is not empty.
Extends
Constructors
new NotEmptyError()
new NotEmptyError(message): NotEmptyError
Creates a new instance.
Parameters
• message: string
The error message.
Returns
NotEmptyError
Overrides
Error.constructor
Defined in
packages/fs/src/error/not-empty-error.ts:9
Accessors
code
get code(): string
set code(_name): void
Parameters
• _name: string
Returns
string
Defined in
packages/fs/src/error/not-empty-error.ts:14
name
get name(): string
set name(_name): void
Parameters
• _name: string
Returns
string
Overrides
Error.name
Defined in
packages/fs/src/error/not-empty-error.ts:24
Methods
captureStackTrace()
static captureStackTrace(targetObject, constructorOpt?): void
Create .stack property on a target object
Parameters
• targetObject: object
• constructorOpt?: Function
Returns
void
Inherited from
Error.captureStackTrace
Defined in
node_modules/.pnpm/@types+node@18.19.15/node_modules/@types/node/globals.d.ts:20
Properties
cause?
optional cause: unknown;
Inherited from
Error.cause
Defined in
node_modules/.pnpm/typescript@5.6.3/node_modules/typescript/lib/lib.es2022.error.d.ts:24
message
message: string;
Inherited from
Error.message
Defined in
node_modules/.pnpm/typescript@5.6.3/node_modules/typescript/lib/lib.es5.d.ts:1077
stack?
optional stack: string;
Inherited from
Error.stack
Defined in
node_modules/.pnpm/typescript@5.6.3/node_modules/typescript/lib/lib.es5.d.ts:1078
prepareStackTrace()?
static optional prepareStackTrace: (err, stackTraces) => any;
Optional override for formatting stack traces
Parameters
• err: Error
• stackTraces: CallSite
[]
Returns
any
See
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
Inherited from
Error.prepareStackTrace
Defined in
node_modules/.pnpm/@types+node@18.19.15/node_modules/@types/node/globals.d.ts:27
stackTraceLimit
static stackTraceLimit: number;
Inherited from
Error.stackTraceLimit
Defined in
node_modules/.pnpm/@types+node@18.19.15/node_modules/@types/node/globals.d.ts:29
NotFoundError
Error thrown when a file or directory is not found.
Extends
Constructors
new NotFoundError()
new NotFoundError(message): NotFoundError
Creates a new instance.
Parameters
• message: string
The error message.
Returns
NotFoundError
Overrides
Error.constructor
Defined in
packages/fs/src/error/not-found-error.ts:9
Accessors
code
get code(): string
set code(_name): void
Parameters
• _name: string
Returns
string
Defined in
packages/fs/src/error/not-found-error.ts:14
name
get name(): string
set name(_name): void
Parameters
• _name: string
Returns
string
Overrides
Error.name
Defined in
packages/fs/src/error/not-found-error.ts:24
Methods
captureStackTrace()
static captureStackTrace(targetObject, constructorOpt?): void
Create .stack property on a target object
Parameters
• targetObject: object
• constructorOpt?: Function
Returns
void
Inherited from
Error.captureStackTrace
Defined in
node_modules/.pnpm/@types+node@18.19.15/node_modules/@types/node/globals.d.ts:20
Properties
cause?
optional cause: unknown;
Inherited from
Error.cause
Defined in
node_modules/.pnpm/typescript@5.6.3/node_modules/typescript/lib/lib.es2022.error.d.ts:24
message
message: string;
Inherited from
Error.message
Defined in
node_modules/.pnpm/typescript@5.6.3/node_modules/typescript/lib/lib.es5.d.ts:1077
stack?
optional stack: string;
Inherited from
Error.stack
Defined in
node_modules/.pnpm/typescript@5.6.3/node_modules/typescript/lib/lib.es5.d.ts:1078
prepareStackTrace()?
static optional prepareStackTrace: (err, stackTraces) => any;
Optional override for formatting stack traces
Parameters
• err: Error
• stackTraces: CallSite
[]
Returns
any
See
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
Inherited from
Error.prepareStackTrace
Defined in
node_modules/.pnpm/@types+node@18.19.15/node_modules/@types/node/globals.d.ts:27
stackTraceLimit
static stackTraceLimit: number;
Inherited from
Error.stackTraceLimit
Defined in
node_modules/.pnpm/@types+node@18.19.15/node_modules/@types/node/globals.d.ts:29
PermissionError
Error thrown when an operation is not permitted.
Extends
Constructors
new PermissionError()
new PermissionError(message): PermissionError
Creates a new instance.
Parameters
• message: string
The error message.
Returns
PermissionError
Overrides
Error.constructor
Defined in
packages/fs/src/error/permission-error.ts:9
Accessors
code
get code(): string
set code(_name): void
Parameters
• _name: string
Returns
string
Defined in
packages/fs/src/error/permission-error.ts:14
name
get name(): string
set name(_name): void
Parameters
• _name: string
Returns
string
Overrides
Error.name
Defined in
packages/fs/src/error/permission-error.ts:24
Methods
captureStackTrace()
static captureStackTrace(targetObject, constructorOpt?): void
Create .stack property on a target object
Parameters
• targetObject: object
• constructorOpt?: Function
Returns
void
Inherited from
Error.captureStackTrace
Defined in
node_modules/.pnpm/@types+node@18.19.15/node_modules/@types/node/globals.d.ts:20
Properties
cause?
optional cause: unknown;
Inherited from
Error.cause
Defined in
node_modules/.pnpm/typescript@5.6.3/node_modules/typescript/lib/lib.es2022.error.d.ts:24
message
message: string;
Inherited from
Error.message
Defined in
node_modules/.pnpm/typescript@5.6.3/node_modules/typescript/lib/lib.es5.d.ts:1077
stack?
optional stack: string;
Inherited from
Error.stack
Defined in
node_modules/.pnpm/typescript@5.6.3/node_modules/typescript/lib/lib.es5.d.ts:1078
prepareStackTrace()?
static optional prepareStackTrace: (err, stackTraces) => any;
Optional override for formatting stack traces
Parameters
• err: Error
• stackTraces: CallSite
[]
Returns
any
See
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
Inherited from
Error.prepareStackTrace
Defined in
node_modules/.pnpm/@types+node@18.19.15/node_modules/@types/node/globals.d.ts:27
stackTraceLimit
static stackTraceLimit: number;
Inherited from
Error.stackTraceLimit
Defined in
node_modules/.pnpm/@types+node@18.19.15/node_modules/@types/node/globals.d.ts:29
WalkError
Error thrown in walk or walkSync during iteration.
Extends
Constructors
new WalkError()
new WalkError(cause, root): WalkError
Constructs a new instance.
Parameters
• cause: unknown
• root: string
Returns
WalkError
Overrides
Error.constructor
Defined in
packages/fs/src/error/walk-error.ts:12
Accessors
name
get name(): string
set name(_name): void
Parameters
• _name: string
Returns
string
Overrides
Error.name
Defined in
packages/fs/src/error/walk-error.ts:21
Methods
captureStackTrace()
static captureStackTrace(targetObject, constructorOpt?): void
Create .stack property on a target object
Parameters
• targetObject: object
• constructorOpt?: Function
Returns
void
Inherited from
Error.captureStackTrace
Defined in
node_modules/.pnpm/@types+node@18.19.15/node_modules/@types/node/globals.d.ts:20
Properties
cause?
optional cause: unknown;
Inherited from
Error.cause
Defined in
node_modules/.pnpm/typescript@5.6.3/node_modules/typescript/lib/lib.es2022.error.d.ts:24
message
message: string;
Inherited from
Error.message
Defined in
node_modules/.pnpm/typescript@5.6.3/node_modules/typescript/lib/lib.es5.d.ts:1077
root
root: string;
File path of the root that's being walked.
Defined in
packages/fs/src/error/walk-error.ts:9
stack?
optional stack: string;
Inherited from
Error.stack
Defined in
node_modules/.pnpm/typescript@5.6.3/node_modules/typescript/lib/lib.es5.d.ts:1078
prepareStackTrace()?
static optional prepareStackTrace: (err, stackTraces) => any;
Optional override for formatting stack traces
Parameters
• err: Error
• stackTraces: CallSite
[]
Returns
any
See
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
Inherited from
Error.prepareStackTrace
Defined in
node_modules/.pnpm/@types+node@18.19.15/node_modules/@types/node/globals.d.ts:27
stackTraceLimit
static stackTraceLimit: number;
Inherited from
Error.stackTraceLimit
Defined in
node_modules/.pnpm/@types+node@18.19.15/node_modules/@types/node/globals.d.ts:29
References
JSONError
Re-exports JSONError
index
Functions
collect()
function collect(directory, options): Promise<string[]>
Parameters
• directory: string
• options: WalkOptions
= {}
Returns
Promise
<string
[]>
Defined in
packages/fs/src/find/collect.ts:4
collectSync()
function collectSync(directory, options): string[]
Parameters
• directory: string
• options: WalkOptions
= {}
Returns
string
[]
Defined in
packages/fs/src/find/collect-sync.ts:4
detect()
function detect(content): "\n" | "\r\n"
Detect the EOL character for string input.
Returns null if no newline.
Parameters
• content: string
Returns
"\n" | "\r\n"
Defined in
packages/fs/src/eol.ts:20
emptyDir()
function emptyDir(dir, options?): Promise<void>
Ensures that a directory is empty.
Deletes directory contents if the directory is not empty.
If the directory does not exist, it is created.
The directory itself is not deleted.
Parameters
• dir: string
| URL
• options?: EmptyDirOptions
Returns
Promise
<void
>
Defined in
packages/fs/src/remove/empty-dir.ts:19
emptyDirSync()
function emptyDirSync(dir, options?): void
Ensures that a directory is empty.
Deletes directory contents if the directory is not empty.
If the directory does not exist, it is created.
The directory itself is not deleted.
Parameters
• dir: string
| URL
• options?: EmptyDirOptions
Returns
void
Defined in
packages/fs/src/remove/empty-dir-sync.ts:18
ensureDir()
function ensureDir(directory): Promise<void>
Ensures that the directory exists.
If the directory structure does not exist, it is created. Like mkdir -p.
Parameters
• directory: string
| URL
Returns
Promise
<void
>
Defined in
packages/fs/src/ensure/ensure-dir.ts:12
ensureDirSync()
function ensureDirSync(directory): void
Ensures that the directory exists.
If the directory structure does not exist, it is created. Like mkdir -p.
Parameters
• directory: string
| URL
Returns
void
Defined in
packages/fs/src/ensure/ensure-dir-sync.ts:12
ensureFile()
function ensureFile(filePath): Promise<void>
Ensures that the file exists.
If the file that is requested to be created is in directories that do not exist,
these directories are created. If the file already exists, it is NOTMODIFIED.
Parameters
• filePath: string
| URL
Returns
Promise
<void
>
Defined in
packages/fs/src/ensure/ensure-file.ts:16
ensureFileSync()
function ensureFileSync(filePath): void
Ensures that the file exists.
If the file that is requested to be created is in directories that do not exist,
these directories are created. If the file already exists, it is NOTMODIFIED.
Parameters
• filePath: string
| URL
Returns
void
Defined in
packages/fs/src/ensure/ensure-file-sync.ts:16
ensureLink()
function ensureLink(source, destination): Promise<void>
Ensures that the hard link exists.
If the directory structure does not exist, it is created.
Parameters
• source: string
| URL
• destination: string
| URL
Returns
Promise
<void
>
Defined in
packages/fs/src/ensure/ensure-link.ts:15
ensureLinkSync()
function ensureLinkSync(source, destination): void
Ensures that the hard link exists.
If the directory structure does not exist, it is created.
Parameters
• source: string
| URL
• destination: string
| URL
Returns
void
Defined in
packages/fs/src/ensure/ensure-link-sync.ts:15
ensureSymlink()
function ensureSymlink(
target,
linkName,
type?): Promise<void>
Ensures that the link exists, and points to a valid file.
If the directory structure does not exist, it is created.
If the link already exists, it is not modified but error is thrown if it is not point to the given target.
Parameters
• target: string
| URL
the source file path
• linkName: string
| URL
the destination link path
• type?: Type
the type of the symlink, or null to use automatic detection
Returns
Promise
<void
>
A void promise that resolves once the link exists.
Defined in
packages/fs/src/ensure/ensure-symlink.ts:28
ensureSymlinkSync()
function ensureSymlinkSync(
target,
linkName,
type?): void
Ensures that the link exists, and points to a valid file.
If the directory structure does not exist, it is created.
If the link already exists, it is not modified but error is thrown if it is not point to the given target.
Parameters
• target: string
| URL
the source file path
• linkName: string
| URL
the destination link path
• type?: Type
the type of the symlink, or null to use automatic detection
Returns
void
A void.
Defined in
packages/fs/src/ensure/ensure-symlink-sync.ts:28
findUp()
function findUp(name, options): Promise<string>
Parameters
• name: FindUpName
• options: FindUpOptions
= {}
Returns
Promise
<string
>
Defined in
packages/fs/src/find/find-up.ts:11
findUpSync()
function findUpSync(name, options): string
Parameters
• name: FindUpNameSync
• options: FindUpOptions
= {}
Returns
string
Defined in
packages/fs/src/find/find-up-sync.ts:11
format()
function format(content, eol): string
Format the file to the targeted EOL.
Parameters
• content: string
• eol: "\n" | "\r\n"
Returns
string
Defined in
packages/fs/src/eol.ts:36
isAccessible()
function isAccessible(path, mode?): Promise<boolean>
Returns a Promise that resolves to a boolean indicating if the path is accessible or not.
Parameters
• path: string
| URL
• mode?: number
Returns
Promise
<boolean
>
Defined in
packages/fs/src/is-accessible.ts:9
isAccessibleSync()
function isAccessibleSync(path, mode?): boolean
Returns a boolean indicating if the path is accessible or not.
Parameters
• path: string
| URL
• mode?: number
Returns
boolean
Defined in
packages/fs/src/is-accessible-sync.ts:9
move()
function move(
sourcePath,
destinationPath,
options): Promise<void>
Move a file asynchronously.
Parameters
• sourcePath: string
The file you want to move.
• destinationPath: string
Where you want the file moved.
• options: MoveOptions
= {}
Configuration options.
Returns
Promise
<void
>
A Promise
that resolves when the file has been moved.
Example
import { moveFile } from '@visulima/fs';
await moveFile('source/test.png', 'destination/test.png');
console.log('The file has been moved');
Defined in
packages/fs/src/move/index.ts:35
moveSync()
function moveSync(
sourcePath,
destinationPath,
options?): void
Move a file synchronously.
Parameters
• sourcePath: string
The file you want to move.
• destinationPath: string
Where you want the file moved.
• options?: MoveOptions
Configuration options.
Returns
void
Nothing is returned.
Example
import { moveFileSync } from '@visulima/fs';
moveFileSync('source/test.png', 'destination/test.png');
console.log('The file has been moved');
Defined in
packages/fs/src/move/index.ts:61
readFile()
function readFile<O>(path, options?): Promise<ContentType<O>>
Type Parameters
• O extends ReadFileOptions
<"brotli"
| "gzip"
| "none"
> = undefined
Parameters
• path: string
| URL
• options?: O
Returns
Promise
<ContentType
<O
>>
Defined in
packages/fs/src/read/read-file.ts:20
readFileSync()
function readFileSync<O>(path, options?): ContentType<O>
Type Parameters
• O extends ReadFileOptions
<"brotli"
| "gzip"
| "none"
> = undefined
Parameters
• path: string
| URL
• options?: O
Returns
ContentType
<O
>
Defined in
packages/fs/src/read/read-file-sync.ts:18
readJson()
readJson(path, options)
function readJson<T>(path, options?): Promise<T>
Type Parameters
• T extends JsonValue
Parameters
• path: string
| URL
• options?: ReadJsonOptions
Returns
Promise
<T
>
Defined in
packages/fs/src/read/read-json.ts:8
readJson(path, reviver, options)
function readJson<T>(
path,
reviver,
options?): Promise<T>
Type Parameters
• T extends JsonValue
Parameters
• path: string
| URL
• reviver
• options?: ReadJsonOptions
Returns
Promise
<T
>
Defined in
packages/fs/src/read/read-json.ts:10
readJsonSync()
readJsonSync(path, options)
function readJsonSync<T>(path, options?): T
Type Parameters
• T extends JsonValue
Parameters
• path: string
| URL
• options?: ReadJsonOptions
Returns
T
Defined in
packages/fs/src/read/read-json-sync.ts:8
readJsonSync(path, reviver, options)
function readJsonSync<T>(
path,
reviver,
options?): T
Type Parameters
• T extends JsonValue
Parameters
• path: string
| URL
• reviver
• options?: ReadJsonOptions
Returns
T
Defined in
packages/fs/src/read/read-json-sync.ts:10
readYaml()
readYaml(path, options)
function readYaml<R>(path, options?): Promise<R>
Type Parameters
• R = Record
<string
, unknown
>
Parameters
• path: string
| URL
• options?: ReadYamlOptions
<"brotli"
| "gzip"
| "none"
>
Returns
Promise
<R
>
Defined in
packages/fs/src/read/read-yaml.ts:6
readYaml(path, reviver, options)
function readYaml<R>(
path,
reviver?,
options?): Promise<R>
Type Parameters
• R = Record
<string
, unknown
>
Parameters
• path: string
| URL
• reviver?: YamlReviver
• options?: ReadYamlOptions
<"brotli"
| "gzip"
| "none"
>
Returns
Promise
<R
>
Defined in
packages/fs/src/read/read-yaml.ts:7
readYamlSync()
readYamlSync(path, options)
function readYamlSync<R>(path, options?): R
Type Parameters
• R = Record
<string
, unknown
>
Parameters
• path: string
| URL
• options?: ReadYamlOptions
<"brotli"
| "gzip"
| "none"
>
Returns
R
Defined in
packages/fs/src/read/read-yaml-sync.ts:6
readYamlSync(path, reviver, options)
function readYamlSync<R>(
path,
reviver?,
options?): R
Type Parameters
• R = Record
<string
, unknown
>
Parameters
• path: string
| URL
• reviver?: YamlReviver
• options?: ReadYamlOptions
<"brotli"
| "gzip"
| "none"
>
Returns
R
Defined in
packages/fs/src/read/read-yaml-sync.ts:7
remove()
function remove(path, options): Promise<void>
Parameters
• path: string
| URL
• options = {}
• options.maxRetries?: number
If an EBUSY
, EMFILE
, ENFILE
, ENOTEMPTY
, or
EPERM
error is encountered, Node.js will retry the operation with a linear
backoff wait of retryDelay
ms longer on each try. This option represents the
number of retries. This option is ignored if the recursive
option is not
true
.
Default
0
• options.retryDelay?: number
The amount of time in milliseconds to wait between retries.
This option is ignored if the recursive
option is not true
.
Default
100
Returns
Promise
<void
>
Defined in
packages/fs/src/remove/remove.ts:5
removeSync()
function removeSync(path, options): void
Parameters
• path: string
| URL
• options = {}
• options.maxRetries?: number
If an EBUSY
, EMFILE
, ENFILE
, ENOTEMPTY
, or
EPERM
error is encountered, Node.js will retry the operation with a linear
backoff wait of retryDelay
ms longer on each try. This option represents the
number of retries. This option is ignored if the recursive
option is not
true
.
Default
0
• options.retryDelay?: number
The amount of time in milliseconds to wait between retries.
This option is ignored if the recursive
option is not true
.
Default
100
Returns
void
Defined in
packages/fs/src/remove/remove-sync.ts:5
rename()
function rename(
source,
destination,
options?): Promise<void>
Rename a file asynchronously.
Parameters
• source: string
The file you want to rename.
• destination: string
The name of the renamed file.
• options?: MoveOptions
Configuration options.
Returns
Promise
<void
>
A Promise
that resolves when the file has been renamed.
Example
import { renameFile } from '@visulima/fs';
await renameFile('test.png', 'tests.png', {cwd: 'source'});
console.log('The file has been renamed');
Defined in
packages/fs/src/move/index.ts:85
renameSync()
function renameSync(
source,
destination,
options?): void
Rename a file synchronously.
Parameters
• source: string
The file you want to rename.
• destination: string
The name of the renamed file.
• options?: MoveOptions
Configuration options.
Returns
void
A Promise
that resolves when the file has been renamed.
Example
import {renameFileSync} from '@visulima/fs';
renameFileSync('test.png', 'tests.png', {cwd: 'source'});
console.log('The file has been renamed');
Defined in
packages/fs/src/move/index.ts:109
walk()
function walk(directory, __namedParameters): AsyncIterableIterator<WalkEntry>
Walks the file tree rooted at root, yielding each file or directory in the
tree filtered according to the given options.
Options:
- maxDepth?: number = Infinity;
- includeFiles?: boolean = true;
- includeDirs?: boolean = true;
- includeSymlinks?: boolean = true;
- followSymlinks?: boolean = false;
- extensions?: string[];
- match?: string | ReadonlyArray;
- skip?: string | ReadonlyArray;
Parameters
• directory: string
| URL
• __namedParameters: WalkOptions
= {}
Returns
AsyncIterableIterator
<WalkEntry
>
Defined in
packages/fs/src/find/walk.ts:52
walkSync()
function walkSync(directory, __namedParameters): IterableIterator<WalkEntry>
Same as walk
but uses synchronous ops
Parameters
• directory: string
| URL
• __namedParameters: WalkOptions
= {}
Returns
IterableIterator
<WalkEntry
>
Defined in
packages/fs/src/find/walk-sync.ts:40
writeFile()
function writeFile(
path,
content,
options?): Promise<void>
Parameters
• path: string
| URL
• content: string
| ArrayBuffer
| ArrayBufferView
• options?: WriteFileOptions
Returns
Promise
<void
>
Defined in
packages/fs/src/write/write-file.ts:15
writeFileSync()
function writeFileSync(
path,
content,
options?): void
Parameters
• path: string
| URL
• content: string
| ArrayBuffer
| ArrayBufferView
• options?: WriteFileOptions
Returns
void
Defined in
packages/fs/src/write/write-file-sync.ts:15
writeJson()
function writeJson(
path,
data,
options): Promise<void>
Parameters
• path: string
| URL
• data: unknown
• options: WriteJsonOptions
= {}
Returns
Promise
<void
>
Defined in
packages/fs/src/write/write-json.ts:11
writeJsonSync()
function writeJsonSync(
path,
data,
options): void
Parameters
• path: string
| URL
• data: unknown
• options: WriteJsonOptions
= {}
Returns
void
Defined in
packages/fs/src/write/write-json-sync.ts:11
writeYaml()
writeYaml(path, data, options)
function writeYaml(
path,
data,
options?): Promise<void>
Parameters
• path: string
| URL
• data: any
• options?: Options
Returns
Promise
<void
>
Defined in
packages/fs/src/write/write-yaml.ts:10
writeYaml(path, data, replacer, options)
function writeYaml(
path,
data,
replacer?,
options?): Promise<void>
Parameters
• path: string
| URL
• data: any
• replacer?: JsonReplacer
• options?: string
| number
| Options
Returns
Promise
<void
>
Defined in
packages/fs/src/write/write-yaml.ts:16
writeYamlSync()
writeYamlSync(path, data, options)
function writeYamlSync(
path,
data,
options?): void
Parameters
• path: string
| URL
• data: any
• options?: Options
Returns
void
Defined in
packages/fs/src/write/write-yaml-sync.ts:10
writeYamlSync(path, data, replacer, options)
function writeYamlSync(
path,
data,
replacer?,
options?): void
Parameters
• path: string
| URL
• data: any
• replacer?: JsonReplacer
• options?: string
| number
| Options
Returns
void
Defined in
packages/fs/src/write/write-yaml-sync.ts:16
Variables
CRLF
const CRLF: "\r\n";
End-of-line character for Windows platforms.
Defined in
packages/fs/src/eol.ts:9
EOL
const EOL: "\n" | "\r\n";
End-of-line character evaluated for the current platform.
Defined in
packages/fs/src/eol.ts:14
F_OK
const F_OK: 0 = 0;
Is the path visible to the calling process?
Defined in
packages/fs/src/constants.ts:2
FIND_UP_STOP
const FIND_UP_STOP: typeof FIND_UP_STOP;
Defined in
packages/fs/src/constants.ts:13
LF
const LF: "\n";
End-of-line character for POSIX platforms such as macOS and Linux.
Defined in
packages/fs/src/eol.ts:6
R_OK
const R_OK: 4 = 4;
Is the path readable to the calling process?
Defined in
packages/fs/src/constants.ts:5
W_OK
const W_OK: 2 = 2;
Is the path writable to the calling process?
Defined in
packages/fs/src/constants.ts:8
X_OK
const X_OK: 1 = 1;
Is the path executable to the calling process?
Defined in
packages/fs/src/constants.ts:11
Interfaces
WalkEntry
Extends
Pick
<Dirent
, "isDirectory"
| "isFile"
| "isSymbolicLink"
| "name"
>
Methods
isDirectory()
isDirectory(): boolean
Returns true
if the fs.Dirent
object describes a file system
directory.
Returns
boolean
Since
v10.10.0
Inherited from
Pick.isDirectory
Defined in
node_modules/.pnpm/@types+node@18.19.15/node_modules/@types/node/fs.d.ts:190
isFile()
isFile(): boolean
Returns true
if the fs.Dirent
object describes a regular file.
Returns
boolean
Since
v10.10.0
Inherited from
Pick.isFile
Defined in
node_modules/.pnpm/@types+node@18.19.15/node_modules/@types/node/fs.d.ts:184
isSymbolicLink()
isSymbolicLink(): boolean
Returns true
if the fs.Dirent
object describes a symbolic link.
Returns
boolean
Since
v10.10.0
Inherited from
Pick.isSymbolicLink
Defined in
node_modules/.pnpm/@types+node@18.19.15/node_modules/@types/node/fs.d.ts:205
Properties
name
name: string;
The file name that this fs.Dirent
object refers to. The type of this
value is determined by the options.encoding
passed to readdir or readdirSync.
Since
v10.10.0
Inherited from
Pick.name
Defined in
node_modules/.pnpm/@types+node@18.19.15/node_modules/@types/node/fs.d.ts:222
path
path: string;
Defined in
packages/fs/src/types.ts:57
WalkOptions
Properties
extensions?
optional extensions: string[];
List of file extensions used to filter entries.
If specified, entries without the file extension specified by this option are excluded.
Default
{undefined}
Defined in
packages/fs/src/types.ts:15
followSymlinks?
optional followSymlinks: boolean;
Indicates whether symlinks should be resolved or not.
Default
{false}
Defined in
packages/fs/src/types.ts:20
includeDirs?
optional includeDirs: boolean;
Indicates whether directory entries should be included or not.
Default
{true}
Defined in
packages/fs/src/types.ts:25
includeFiles?
optional includeFiles: boolean;
Indicates whether file entries should be included or not.
Default
{true}
Defined in
packages/fs/src/types.ts:30
includeSymlinks?
optional includeSymlinks: boolean;
Indicates whether symlink entries should be included or not.
This option is meaningful only if followSymlinks
is set to false
.
Default
{true}
Defined in
packages/fs/src/types.ts:36
match?
optional match: (string | RegExp)[];
List of regular expression or glob patterns used to filter entries.
If specified, entries that do not match the patterns specified by this option are excluded.
Default
{undefined}
Defined in
packages/fs/src/types.ts:42
maxDepth?
optional maxDepth: number;
The maximum depth of the file tree to be walked recursively.
Default
{Infinity}
Defined in
packages/fs/src/types.ts:47
skip?
optional skip: (string | RegExp)[];
List of regular expression or glob patterns used to filter entries.
If specified, entries matching the patterns specified by this option are excluded.
Default
{undefined}
Defined in
packages/fs/src/types.ts:53
Type Aliases
CodeFrameLocation
type CodeFrameLocation: object;
Type declaration
column?
optional column: number;
line
line: number;
Defined in
packages/fs/src/types.ts:91
EmptyDirOptions
type EmptyDirOptions: object;
Type declaration
maxRetries?
optional maxRetries: number;
If an EBUSY
, EMFILE
, ENFILE
, ENOTEMPTY
, or
EPERM
error is encountered, Node.js will retry the operation with a linear
backoff wait of retryDelay
ms longer on each try. This option represents the
number of retries. This option is ignored if the recursive
option is not
true
.
Default
0
retryDelay?
optional retryDelay: number;
The amount of time in milliseconds to wait between retries.
This option is ignored if the recursive
option is not true
.
Default
100
Defined in
packages/fs/src/types.ts:188
FindUpName
type FindUpName: string[] | string | (directory) => FindUpNameFnResult;
Defined in
packages/fs/src/types.ts:180
FindUpNameFnResult
type FindUpNameFnResult: PathLike | Promise<PathLike | typeof FIND_UP_STOP> | typeof FIND_UP_STOP | undefined;
Defined in
packages/fs/src/types.ts:178
FindUpNameSync
type FindUpNameSync: string[] | string | (directory) => FindUpNameSyncFnResult;
Defined in
packages/fs/src/types.ts:185
FindUpNameSyncFnResult
type FindUpNameSyncFnResult: PathLike | typeof FIND_UP_STOP | undefined;
Defined in
packages/fs/src/types.ts:183
FindUpOptions
type FindUpOptions: object;
Type declaration
allowSymlinks?
optional allowSymlinks: boolean;
cwd?
optional cwd: URL | string;
stopAt?
optional stopAt: URL | string;
type?
optional type: "directory" | "file";
Defined in
packages/fs/src/types.ts:170
JsonReplacer
type JsonReplacer: (number | string)[] | (this, key, value) => unknown | null;
Defined in
packages/fs/src/types.ts:143
JsonReviver
type JsonReviver: Parameters<typeof JSON["parse"]>["1"];
Defined in
packages/fs/src/types.ts:89
MoveOptions
type MoveOptions: object;
Type declaration
cwd?
optional cwd: URL | string;
The working directory to find source files.
The source and destination path are relative to this.
Default
process.cwd()
directoryMode?
readonly optional directoryMode: FilePermissions;
Permissions for created directories.
It has no effect on Windows.
Default
0o777
overwrite?
readonly optional overwrite: boolean;
Overwrite existing destination file.
Default
true
Defined in
packages/fs/src/move/types.ts:3
ReadFileEncoding
type ReadFileEncoding:
| "ascii"
| "base64"
| "base64url"
| "hex"
| "latin1"
| "ucs-2"
| "ucs2"
| "utf-8"
| "utf-16le"
| "utf8"
| "utf16le";
Defined in
packages/fs/src/types.ts:61
ReadFileOptions<C>
type ReadFileOptions<C>: object;
Type Parameters
• C
Type declaration
buffer?
optional buffer: boolean;
Return content as a Buffer. Default: false
compression?
optional compression: C;
Compression method to decompress the file against. Default: none
encoding?
optional encoding: ReadFileEncoding;
The encoding to use. Default: utf8
See
https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings
flag?
optional flag: number | string;
The flag used to open the file. Default: r
Defined in
packages/fs/src/types.ts:63
ReadJsonOptions
type ReadJsonOptions: CodeFrameOptions & object;
Type declaration
beforeParse()?
optional beforeParse: (source) => string;
Parameters
• source: string
Returns
string
Defined in
packages/fs/src/types.ts:104
WriteFileOptions
type WriteFileOptions: object;
Type declaration
chown?
optional chown: object;
The group and user ID used to set the file ownership. Default: undefined
chown.gid
gid: number;
chown.uid
uid: number;
encoding?
optional encoding: BufferEncoding | null;
The encoding to use. Default: utf8
flag?
optional flag: string;
The flag used to write the file. Default: w
mode?
optional mode: number;
The file mode (permission and sticky bits). Default: 0o666
overwrite?
optional overwrite: boolean;
Indicates whether the file should be overwritten if it already exists. Default: false
recursive?
optional recursive: boolean;
Recursively create parent directories if needed. Default: true
Defined in
packages/fs/src/types.ts:108
WriteJsonOptions
type WriteJsonOptions: WriteFileOptions & object;
Type declaration
detectIndent?
optional detectIndent: boolean;
Detect indentation automatically if the file exists. Default: false
indent?
optional indent: number | string;
The space used for pretty-printing.
Pass in undefined
for no formatting.
replacer?
optional replacer: JsonReplacer;
Passed into JSON.stringify
.
stringify()?
optional stringify: (data, replacer, space) => string;
Override the default JSON.stringify
method.
Parameters
• data: unknown
• replacer: JsonReplacer
• space: number
| string
| undefined
Returns
string
Defined in
packages/fs/src/types.ts:146
YamlReplacer
type YamlReplacer: JsonReplacer;
Defined in
packages/fs/src/types.ts:144
utils
Classes
JSONError
Extends
Constructors
new JSONError()
new JSONError(message): JSONError
Parameters
• message: string
Returns
JSONError
Overrides
Error.constructor
Defined in
packages/fs/src/error/json-error.ts:11
Accessors
message
get message(): string
set message(message): void
Parameters
• message: string
Returns
string
Overrides
Error.message
Defined in
packages/fs/src/error/json-error.ts:21
Methods
captureStackTrace()
static captureStackTrace(targetObject, constructorOpt?): void
Create .stack property on a target object
Parameters
• targetObject: object
• constructorOpt?: Function
Returns
void
Inherited from
Error.captureStackTrace
Defined in
node_modules/.pnpm/@types+node@18.19.15/node_modules/@types/node/globals.d.ts:20
Properties
cause?
optional cause: unknown;
Inherited from
Error.cause
Defined in
node_modules/.pnpm/typescript@5.6.3/node_modules/typescript/lib/lib.es2022.error.d.ts:24
codeFrame
codeFrame: string;
Defined in
packages/fs/src/error/json-error.ts:4
fileName
fileName: string;
Defined in
packages/fs/src/error/json-error.ts:2
name
readonly name: "JSONError" = "JSONError";
Overrides
Error.name
Defined in
packages/fs/src/error/json-error.ts:7
stack?
optional stack: string;
Inherited from
Error.stack
Defined in
node_modules/.pnpm/typescript@5.6.3/node_modules/typescript/lib/lib.es5.d.ts:1078
prepareStackTrace()?
static optional prepareStackTrace: (err, stackTraces) => any;
Optional override for formatting stack traces
Parameters
• err: Error
• stackTraces: CallSite
[]
Returns
any
See
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
Inherited from
Error.prepareStackTrace
Defined in
node_modules/.pnpm/@types+node@18.19.15/node_modules/@types/node/globals.d.ts:27
stackTraceLimit
static stackTraceLimit: number;
Inherited from
Error.stackTraceLimit
Defined in
node_modules/.pnpm/@types+node@18.19.15/node_modules/@types/node/globals.d.ts:29
Functions
assertValidFileContents()
function assertValidFileContents(contents): void
Parameters
• contents: any
Returns
void
Defined in
packages/fs/src/utils/assert-valid-file-contents.ts:2
assertValidFileOrDirectoryPath()
function assertValidFileOrDirectoryPath(fileOrDirectoryPath): void
Parameters
• fileOrDirectoryPath: any
Returns
void
Defined in
packages/fs/src/utils/assert-valid-file-or-directory-path.ts:2
parseJson()
parseJson(string, filename, options)
function parseJson<T>(
string,
filename?,
options?): T
Type Parameters
• T = JsonValue
Parameters
• string: string
• filename?: string
• options?: CodeFrameOptions
Returns
T
Defined in
packages/fs/src/utils/parse-json.ts:60
parseJson(string, reviver, fileName, options)
function parseJson<T>(
string,
reviver,
fileName?,
options?): T
Type Parameters
• T = JsonValue
Parameters
• string: string
• reviver
• fileName?: string
• options?: CodeFrameOptions
Returns
T
Defined in
packages/fs/src/utils/parse-json.ts:61
function stripJsonComments(jsonString, __namedParameters): string
Parameters
• jsonString: string
• __namedParameters = {}
• __namedParameters.whitespace: boolean
= true
Returns
string
Defined in
packages/fs/src/utils/strip-json-comments.ts:5
toPath()
function toPath(urlOrPath): string
Parameters
• urlOrPath: string
| URL
Returns
string
Defined in
node_modules/.pnpm/@visulima+path@1.1.1/node_modules/@visulima/path/dist/utils.d.mts:7
Supported Node.js Versions
Libraries in this ecosystem make the best effort to track Node.js’ release schedule.
Here’s a post on why we think this is important.
Contributing
If you would like to help take a look at the list of issues and check our Contributing guild.
Note: please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.
Credits
About
Related Projects
- strip-json-comments - Strip comments from JSON. Lets you use comments in your JSON files!
- parse-json - Parse JSON with more helpful errors.
- find-up - Find a file or directory by walking up parent directories.
- walk - Walk a directory recursively and yield all files and directories.
License
The visulima fs is open-sourced software licensed under the MIT