Gathering detailed insights and metrics for @visulima/fs
Gathering detailed insights and metrics for @visulima/fs
Gathering detailed insights and metrics for @visulima/fs
Gathering detailed insights and metrics for @visulima/fs
@visulima/pail
Highly configurable Logger for Node.js, Edge and Browser.
@ffras4vnpm/enim-recusandae-assumenda
<p align="center"> <a href="https://visulima.com"> <picture> <source media="(prefers-color-scheme: dark)" srcset=""> <img src="" height="128"> </picture> <h1 align="center">Visulima</h1> </a> </p>
@micromint1npm/voluptate-incidunt-occaecati
<p align="center"> <a href="https://visulima.com"> <picture> <source media="(prefers-color-scheme: dark)" srcset=""> <img src="" height="128"> </picture> <h1 align="center">Visulima</h1> </a> </p>
Visulima provides robust, developer-focused tools and libraries to streamline your workflow. Let us handle the complexities so you can focus on building what truly matters.
npm install @visulima/fs
Typescript
Module System
Min. Node Version
Node Version
NPM Version
85.9
Supply Chain
99.6
Quality
85
Maintenance
100
Vulnerability
99.6
License
@visulima/cerebro@1.1.46
Updated on Jun 04, 2025
@visulima/boxen@2.0.2
Updated on Jun 04, 2025
@visulima/pail@2.1.25
Updated on Jun 04, 2025
@visulima/api-platform@3.0.44
Updated on Jun 04, 2025
@visulima/jsdoc-open-api@2.0.81
Updated on Jun 04, 2025
@visulima/find-cache-dir@1.0.31
Updated on Jun 04, 2025
TypeScript (94.59%)
JavaScript (4.83%)
MDX (0.36%)
Handlebars (0.14%)
Shell (0.08%)
Built with Next.js • Fully responsive • SEO optimized • Open source ready
Total Downloads
110,377
Last Day
16
Last Week
1,064
Last Month
6,710
Last Year
97,593
MIT License
16 Stars
2,716 Commits
3 Forks
2 Watchers
17 Branches
3 Contributors
Updated on Sep 07, 2025
Latest Version
3.1.5
Package Id
@visulima/fs@3.1.5
Unpacked Size
389.31 kB
Size
72.21 kB
File Count
145
NPM Version
10.9.2
Node Version
18.20.8
Published on
Jun 04, 2025
Cumulative downloads
Total Downloads
Last Day
-50%
16
Compared to previous day
Last Week
-20.8%
1,064
Compared to previous week
Last Month
-37.4%
6,710
Compared to previous month
Last Year
663.4%
97,593
Compared to previous year
1
1
Human friendly file system utilities for Node.js
[![typescript-image]][typescript-url] [![npm-image]][npm-url] [![license-image]][license-url]
Daniel Bannert's open source work is supported by the community on GitHub Sponsors
1npm install @visulima/fs
1yarn add @visulima/fs
1pnpm add @visulima/fs
Note: If you want to parse or write YAML, you'll need to install
yaml
as well.
1npm install yaml
1yarn add yaml
1pnpm add yaml
After installing
yaml
, you can use thereadYaml
,readYamlSync
andwriteYaml
,writeYamlSync
functions from@visulima/fs/yaml
.
1import { walk } from "@visulima/fs"; 2 3const filesAndFolders: string[] = []; 4 5for await (const index of walk(`${__dirname}/fixtures`, {})) { 6 filesAndFolders.push(index.path); 7} 8 9console.log(filesAndFolders);
1import { walkSync } from "@visulima/fs"; 2 3const filesAndFolders: string[] = []; 4 5for (const index of walkSync(`${__dirname}/fixtures`, {})) { 6 filesAndFolders.push(index.path); 7} 8 9console.log(filesAndFolders);
walk
and walkSync
Type: string
The directory to start from.
Type: object
Type: number
Default: Infinity
Optional: true
Description: The maximum depth of the file tree to be walked recursively.
Type: boolean
Default: true
Optional: true
Description: Indicates whether file entries should be included or not.
Type: boolean
Default: true
Optional: true
Description: Indicates whether directory entries should be included or not.
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.
Type: boolean
Default: false
Optional: true
Description: Indicates whether symlinks should be resolved or not.
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.
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.
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.
Find a file or directory by walking up parent directories.
1import { findUp } from "@visulima/fs"; 2 3// Returns a Promise for the found path or undefined if it could not be found. 4const file = await findUp("package.json"); 5 6console.log(file);
Find a file or directory by walking up parent directories.
1import { findUpSync } from "@visulima/fs"; 2 3// Returns the found path or undefined if it could not be found. 4const file = findUpSync("package.json"); 5 6console.log(file);
findUp
and findUpSync
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.
Type: object
Type: URL | string
Default: process.cwd()
The directory to start from.
Type: string
Default: 'file'
Values: 'file' | 'directory'
The type of path to match.
Type: URL | string
Default: Root directory
A directory path where the search halts if no matches are found before reaching this point.
Type: boolean
Default: true
Allow symbolic links to match if they point to the target file or directory.
Read a file.
1import { readFile } from "@visulima/fs"; 2 3// Returns a Promise for the file contents. 4const file = await readFile("package.json"); 5 6console.log(file);
Read a file.
1import { readFileSync } from "@visulima/fs"; 2 3// Returns the file contents. 4 5const file = readFileSync("package.json"); 6 7console.log(file);
readFile
and readFileSync
Type: string
The path to the file to read.
Type: object
Type: boolean
Default: true
Optional: true
Description: Indicates whether the file contents should be returned as a Buffer or a string.
Type: "brotli" | "gzip" | undefined
Default: undefined
Optional: true
Description: The file compression.
Type: "ascii" | "base64" | "base64url" | "hex" | "latin1" | "ucs-2" | "ucs2" | "utf-8" | "utf-16le" | "utf8" | "utf16le" | undefined
Default: utf8
Optional: true
Type: number | string | undefined
Default: 'r'
Optional: true
Check if a file or directory exists and is accessible.
1import { isAccessible } from "@visulima/fs"; 2 3// Returns a Promise for the result. 4const file = await isAccessible("package.json"); 5 6console.log(file);
Check if a file or directory exists and is accessible.
1import { isAccessibleSync } from "@visulima/fs"; 2 3// Returns the result. 4 5const file = isAccessibleSync("package.json"); 6 7console.log(file);
isAccessible
and isAccessibleSync
Type: string
The path to the file or directory to check.
Type: number
Default: fs.constants.F_OK
Optional: true
Description: The accessibility mode.
Parse JSON with more helpful errors.
1import { parseJson, JSONError } from "@visulima/fs/utils"; 2 3const json = '{\n\t"foo": true,\n}'; 4 5JSON.parse(json); 6/* 7undefined:3 8} 9^ 10SyntaxError: Unexpected token } 11*/ 12 13parseJson(json); 14/* 15JSONError: Unexpected token } in JSON at position 16 while parsing near '{ "foo": true,}' 16 17 1 | { 18 2 | "foo": true, 19> 3 | } 20 | ^ 21*/ 22 23parseJson(json, "foo.json"); 24/* 25JSONError: Unexpected token } in JSON at position 16 while parsing near '{ "foo": true,}' in foo.json 26 27 1 | { 28 2 | "foo": true, 29> 3 | } 30 | ^ 31*/
parseJson
Type: string
The JSON string to parse.
Type: Function
Prescribes how the value originally produced by parsing is transformed, before being returned. See JSON.parse docs for more.
Type: string
The filename to use in error messages.
JSONError
Exposed for use in instanceof
checks.
Type: string
The filename displayed in the error message.
Type: string
The printable section of the JSON which produces the error.
1function detect(content): "\n" | "\r\n";
Defined in: packages/fs/src/eol.ts:29
Detect the EOL character for string input. Returns null if no newline.
string
The string content to detect the EOL from.
"\n" | "\r\n"
1import { detect } from "@visulima/fs/eol"; 2 3detect("Hello\r\nWorld"); // "\r\n" 4detect("Hello\nWorld"); // "\n" 5detect("HelloWorld"); // null
1function format(content, eol): string;
Defined in: packages/fs/src/eol.ts:54
Format the file to the targeted EOL.
string
The string content to format.
The target EOL character.
"\n" | "\r\n"
string
1import { format, LF, CRLF } from "@visulima/fs/eol"; 2 3format("Hello\r\nWorld\nUnix", LF); // "Hello\nWorld\nUnix" 4format("Hello\nWorld\r\nWindows", CRLF); // "Hello\r\nWorld\r\nWindows"
1const CRLF: "\r\n";
Defined in: packages/fs/src/eol.ts:9
End-of-line character for Windows platforms.
1const EOL: "\n" | "\r\n";
Defined in: packages/fs/src/eol.ts:14
End-of-line character evaluated for the current platform.
1const LF: "\n";
Defined in: packages/fs/src/eol.ts:6
End-of-line character for POSIX platforms such as macOS and Linux.
Defined in: packages/fs/src/error/already-exists-error.ts:28
Error thrown when a file or directory already exists at a specified path, and an operation was expecting it not to.
1import { AlreadyExistsError } from "@visulima/fs/error"; // Assuming it's exported from an index or directly 2import { ensureSymlinkSync } from "@visulima/fs"; // Or any function that might throw this 3import { join } from "node:path"; 4 5try { 6 // Example: ensureSymlinkSync might throw this if a file (not a symlink) already exists at linkName 7 // For demonstration, let's assume someFunction internally throws it: 8 const someFunctionThatMightThrow = (path) => { 9 if (path === "/tmp/existing-file.txt") { // Simulate a check 10 throw new AlreadyExistsError(`file already exists at '/tmp/existing-file.txt'`); 11 } 12 } 13 someFunctionThatMightThrow("/tmp/existing-file.txt"); 14} catch (error) { 15 if (error instanceof AlreadyExistsError) { 16 console.error(`Operation failed because path exists: ${error.message}`); 17 console.error(`Error code: ${error.code}`); // EEXIST 18 } else { 19 console.error("An unexpected error occurred:", error); 20 } 21}
Error
1new AlreadyExistsError(message): AlreadyExistsError;
Defined in: packages/fs/src/error/already-exists-error.ts:33
Creates a new instance.
string
The error message.
1Error.constructor
1get code(): string;
Defined in: packages/fs/src/error/already-exists-error.ts:38
string
1set code(_name): void;
Defined in: packages/fs/src/error/already-exists-error.ts:43
string
void
1get name(): string;
Defined in: packages/fs/src/error/already-exists-error.ts:48
string
1set name(_name): void;
Defined in: packages/fs/src/error/already-exists-error.ts:53
string
void
1Error.name
1static captureStackTrace(targetObject, constructorOpt?): void;
Defined in: node_modules/.pnpm/@types+node@18.19.71/node_modules/@types/node/globals.d.ts:91
Create .stack property on a target object
object
Function
void
1Error.captureStackTrace
1optional cause: unknown;
Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es2022.error.d.ts:26
1Error.cause
1message: string;
Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1077
1Error.message
1optional stack: string;
Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1078
1Error.stack
1static optional prepareStackTrace: (err, stackTraces) => any;
Defined in: node_modules/.pnpm/@types+node@18.19.71/node_modules/@types/node/globals.d.ts:98
Optional override for formatting stack traces
Error
CallSite
[]
any
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
1Error.prepareStackTrace
1static stackTraceLimit: number;
Defined in: node_modules/.pnpm/@types+node@18.19.71/node_modules/@types/node/globals.d.ts:100
1Error.stackTraceLimit
Defined in: packages/fs/src/error/directory-error.ts:36
Error thrown when an operation that is not allowed on a directory is attempted. This typically occurs when a file-specific operation is used on a directory path.
1import { DirectoryError } from "@visulima/fs/error"; 2import { readFile } from "@visulima/fs"; // Or any function that might throw this 3import { join } from "node:path"; 4 5const attemptToReadFileFromDir = async () => { 6 try { 7 // Attempting to read a directory as if it were a file 8 // This is a conceptual example; readFile might throw a different error first 9 // depending on its internal checks, but EISDIR is the underlying system error. 10 // Forcing the scenario: 11 const pretendReadFileOnDir = (path) => { 12 if (path === "/tmp/my-directory") { // Simulate a directory path 13 throw new DirectoryError(`read '/tmp/my-directory'`); 14 } 15 } 16 pretendReadFileOnDir("/tmp/my-directory"); 17 // await readFile(join("/tmp", "my-directory")); 18 } catch (error) { 19 if (error instanceof DirectoryError) { 20 console.error(`Operation failed, path is a directory: ${error.message}`); 21 console.error(`Error code: ${error.code}`); // EISDIR 22 } else { 23 console.error("An unexpected error occurred:", error); 24 } 25 } 26}; 27 28attemptToReadFileFromDir();
Error
1new DirectoryError(message): DirectoryError;
Defined in: packages/fs/src/error/directory-error.ts:41
Creates a new instance.
string
The error message.
1Error.constructor
1get code(): string;
Defined in: packages/fs/src/error/directory-error.ts:46
string
1set code(_name): void;
Defined in: packages/fs/src/error/directory-error.ts:51
string
void
1get name(): string;
Defined in: packages/fs/src/error/directory-error.ts:56
string
1set name(_name): void;
Defined in: packages/fs/src/error/directory-error.ts:61
string
void
1Error.name
1static captureStackTrace(targetObject, constructorOpt?): void;
Defined in: node_modules/.pnpm/@types+node@18.19.71/node_modules/@types/node/globals.d.ts:91
Create .stack property on a target object
object
Function
void
1Error.captureStackTrace
1optional cause: unknown;
Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es2022.error.d.ts:26
1Error.cause
1message: string;
Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1077
1Error.message
1optional stack: string;
Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1078
1Error.stack
1static optional prepareStackTrace: (err, stackTraces) => any;
Defined in: node_modules/.pnpm/@types+node@18.19.71/node_modules/@types/node/globals.d.ts:98
Optional override for formatting stack traces
Error
CallSite
[]
any
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
1Error.prepareStackTrace
1static stackTraceLimit: number;
Defined in: node_modules/.pnpm/@types+node@18.19.71/node_modules/@types/node/globals.d.ts:100
1Error.stackTraceLimit
Defined in: packages/fs/src/error/not-empty-error.ts:40
Error thrown when a directory is not empty.
1import { NotEmptyError } from "@visulima/fs/error"; 2import { rmdir } from "node:fs/promises"; // Or any fs function that might throw this system error 3import { join } from "node:path"; 4 5const attemptToRemoveNonEmptyDir = async () => { 6 const dirPath = join("/tmp", "my-non-empty-dir"); // Assume this directory exists and has files 7 try { 8 // Forcing the scenario for demonstration, as rmdir might throw its own specific error. 9 // Node.js fs operations that encounter a non-empty directory when expecting an empty one 10 // typically throw an error with code ENOTEMPTY. 11 const simulateNotEmpty = (path) => { 12 if (path === dirPath) { // Simulate check for non-empty 13 throw new NotEmptyError(`rmdir '${dirPath}'`); 14 } 15 } 16 simulateNotEmpty(dirPath); 17 // await rmdir(dirPath); // This would likely throw an error with code ENOTEMPTY 18 } catch (error) { 19 if (error instanceof NotEmptyError) { 20 console.error(`Operation failed, directory is not empty: ${error.message}`); 21 console.error(`Error code: ${error.code}`); // ENOTEMPTY 22 } else { 23 console.error("An unexpected error occurred:", error); 24 } 25 } 26}; 27 28// You would need to set up a non-empty directory at /tmp/my-non-empty-dir for a real test 29// import { ensureDirSync, writeFileSync } from "@visulima/fs"; 30// ensureDirSync(dirPath); 31// writeFileSync(join(dirPath, "somefile.txt"), "content"); 32 33attemptToRemoveNonEmptyDir();
Error
1new NotEmptyError(message): NotEmptyError;
Defined in: packages/fs/src/error/not-empty-error.ts:45
Creates a new instance.
string
The error message.
1Error.constructor
1get code(): string;
Defined in: packages/fs/src/error/not-empty-error.ts:50
string
1set code(_name): void;
Defined in: packages/fs/src/error/not-empty-error.ts:55
string
void
1get name(): string;
Defined in: packages/fs/src/error/not-empty-error.ts:60
string
1set name(_name): void;
Defined in: packages/fs/src/error/not-empty-error.ts:65
string
void
1Error.name
1static captureStackTrace(targetObject, constructorOpt?): void;
Defined in: node_modules/.pnpm/@types+node@18.19.71/node_modules/@types/node/globals.d.ts:91
Create .stack property on a target object
object
Function
void
1Error.captureStackTrace
1optional cause: unknown;
Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es2022.error.d.ts:26
1Error.cause
1message: string;
Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1077
1Error.message
1optional stack: string;
Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1078
1Error.stack
1static optional prepareStackTrace: (err, stackTraces) => any;
Defined in: node_modules/.pnpm/@types+node@18.19.71/node_modules/@types/node/globals.d.ts:98
Optional override for formatting stack traces
Error
CallSite
[]
any
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
1Error.prepareStackTrace
1static stackTraceLimit: number;
Defined in: node_modules/.pnpm/@types+node@18.19.71/node_modules/@types/node/globals.d.ts:100
1Error.stackTraceLimit
Defined in: packages/fs/src/error/not-found-error.ts:33
Error thrown when a file or directory is not found at a specified path.
1import { NotFoundError } from "@visulima/fs/error"; 2import { readFile } from "@visulima/fs"; // Or any function that might throw this 3import { join } from "node:path"; 4 5const tryReadingNonExistentFile = async () => { 6 const filePath = join("/tmp", "this-file-does-not-exist.txt"); 7 try { 8 // Forcing the scenario for demonstration, as readFile itself would throw this. 9 const simulateNotFound = (path) => { 10 if (path === filePath) { 11 throw new NotFoundError(`no such file or directory, open '${filePath}'`); 12 } 13 } 14 simulateNotFound(filePath); 15 // await readFile(filePath); 16 } catch (error) { 17 if (error instanceof NotFoundError) { 18 console.error(`Operation failed, path not found: ${error.message}`); 19 console.error(`Error code: ${error.code}`); // ENOENT 20 } else { 21 console.error("An unexpected error occurred:", error); 22 } 23 } 24}; 25 26tryReadingNonExistentFile();
Error
1new NotFoundError(message): NotFoundError;
Defined in: packages/fs/src/error/not-found-error.ts:38
Creates a new instance.
string
The error message.
1Error.constructor
1get code(): string;
Defined in: packages/fs/src/error/not-found-error.ts:43
string
1set code(_name): void;
Defined in: packages/fs/src/error/not-found-error.ts:48
string
void
1get name(): string;
Defined in: packages/fs/src/error/not-found-error.ts:53
string
1set name(_name): void;
Defined in: packages/fs/src/error/not-found-error.ts:58
string
void
1Error.name
1static captureStackTrace(targetObject, constructorOpt?): void;
Defined in: node_modules/.pnpm/@types+node@18.19.71/node_modules/@types/node/globals.d.ts:91
Create .stack property on a target object
object
Function
void
1Error.captureStackTrace
1optional cause: unknown;
Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es2022.error.d.ts:26
1Error.cause
1message: string;
Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1077
1Error.message
1optional stack: string;
Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1078
1Error.stack
1static optional prepareStackTrace: (err, stackTraces) => any;
Defined in: node_modules/.pnpm/@types+node@18.19.71/node_modules/@types/node/globals.d.ts:98
Optional override for formatting stack traces
Error
CallSite
[]
any
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
1Error.prepareStackTrace
1static stackTraceLimit: number;
Defined in: node_modules/.pnpm/@types+node@18.19.71/node_modules/@types/node/globals.d.ts:100
1Error.stackTraceLimit
Defined in: packages/fs/src/error/permission-error.ts:34
Error thrown when an operation is not permitted due to insufficient privileges or other access control restrictions.
1import { PermissionError } from "@visulima/fs/error"; 2import { writeFile } from "@visulima/fs"; // Or any function that might throw this 3import { join } from "node:path"; 4 5const tryWritingToProtectedFile = async () => { 6 const filePath = join("/root", "protected-file.txt"); // A path that typically requires root privileges 7 try { 8 // Forcing the scenario for demonstration, as writeFile itself would throw this. 9 const simulatePermissionError = (path) => { 10 if (path === filePath) { 11 throw new PermissionError(`open '${filePath}'`); 12 } 13 } 14 simulatePermissionError(filePath); 15 // await writeFile(filePath, "test content"); 16 } catch (error) { 17 if (error instanceof PermissionError) { 18 console.error(`Operation not permitted: ${error.message}`); 19 console.error(`Error code: ${error.code}`); // EPERM 20 } else { 21 console.error("An unexpected error occurred:", error); 22 } 23 } 24}; 25 26tryWritingToProtectedFile();
Error
1new PermissionError(message): PermissionError;
Defined in: packages/fs/src/error/permission-error.ts:39
Creates a new instance.
string
The error message.
1Error.constructor
1get code(): string;
Defined in: packages/fs/src/error/permission-error.ts:44
string
1set code(_name): void;
Defined in: packages/fs/src/error/permission-error.ts:49
string
void
1get name(): string;
Defined in: packages/fs/src/error/permission-error.ts:54
string
1set name(_name): void;
Defined in: packages/fs/src/error/permission-error.ts:59
string
void
1Error.name
1static captureStackTrace(targetObject, constructorOpt?): void;
Defined in: node_modules/.pnpm/@types+node@18.19.71/node_modules/@types/node/globals.d.ts:91
Create .stack property on a target object
object
Function
void
1Error.captureStackTrace
1optional cause: unknown;
Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es2022.error.d.ts:26
1Error.cause
1message: string;
Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1077
1Error.message
1optional stack: string;
Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1078
1Error.stack
1static optional prepareStackTrace: (err, stackTraces) => any;
Defined in: node_modules/.pnpm/@types+node@18.19.71/node_modules/@types/node/globals.d.ts:98
Optional override for formatting stack traces
Error
CallSite
[]
any
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
1Error.prepareStackTrace
1static stackTraceLimit: number;
Defined in: node_modules/.pnpm/@types+node@18.19.71/node_modules/@types/node/globals.d.ts:100
1Error.stackTraceLimit
Defined in: packages/fs/src/error/walk-error.ts:43
Error thrown in walk or walkSync during iteration.
1import { WalkError } from "@visulima/fs/error"; 2import { walk } from "@visulima/fs"; 3import { join } from "node:path"; 4 5const processDirectory = async () => { 6 const dirToWalk = join("/tmp", "non-existent-or-permission-denied-dir"); 7 try { 8 // Forcing the scenario: walk might throw a WalkError if it encounters an issue 9 // like a directory it cannot read during the walk process. 10 const simulateWalkError = async (rootDir) => { 11 // Let's say readdir inside walk fails for a subdirectory. 12 const underlyingError = new Error("Permission denied reading subdirectory"); 13 throw new WalkError(underlyingError, rootDir); 14 } 15 // This is conceptual. In a real scenario, 'walk' itself would throw. 16 // for await (const entry of walk(dirToWalk)) { 17 // console.log(entry.path); 18 // } 19 await simulateWalkError(dirToWalk); 20 } catch (error) { 21 if (error instanceof WalkError) { 22 console.error(`Error during directory walk of "${error.root}": ${error.message}`); 23 if (error.cause) { 24 console.error(`Underlying cause: ${error.cause}`); 25 } 26 } else { 27 console.error("An unexpected error occurred:", error); 28 } 29 } 30}; 31 32processDirectory();
Error
1new WalkError(cause, root): WalkError;
Defined in: packages/fs/src/error/walk-error.ts:52
Constructs a new instance.
unknown
The underlying error or reason for the walk failure.
string
The root directory path where the walk operation started or encountered the error.
1Error.constructor
1get name(): string;
Defined in: packages/fs/src/error/walk-error.ts:61
string
1set name(_name): void;
Defined in: packages/fs/src/error/walk-error.ts:66
string
void
1Error.name
1static captureStackTrace(targetObject, constructorOpt?): void;
Defined in: node_modules/.pnpm/@types+node@18.19.71/node_modules/@types/node/globals.d.ts:91
Create .stack property on a target object
object
Function
void
1Error.captureStackTrace
1optional cause: unknown;
Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es2022.error.d.ts:26
1Error.cause
1message: string;
Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1077
1Error.message
1root: string;
Defined in: packages/fs/src/error/walk-error.ts:45
File path of the root that's being walked.
1optional stack: string;
Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1078
1Error.stack
1static optional prepareStackTrace: (err, stackTraces) => any;
Defined in: node_modules/.pnpm/@types+node@18.19.71/node_modules/@types/node/globals.d.ts:98
Optional override for formatting stack traces
Error
CallSite
[]
any
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
1Error.prepareStackTrace
1static stackTraceLimit: number;
Defined in: node_modules/.pnpm/@types+node@18.19.71/node_modules/@types/node/globals.d.ts:100
1Error.stackTraceLimit
Re-exports JSONError
1function collect(directory, options): Promise<string[]>;
Defined in: packages/fs/src/find/collect.ts:37
Asynchronously collects all file paths within a directory that match the specified criteria. By default, it searches for JavaScript and TypeScript file extensions.
string
The root directory to start collecting files from.
WalkOptions
= {}
Optional configuration to control the collection process. See WalkOptions.
Promise
<string
[]>
A promise that resolves to an array of absolute file paths.
1import { collect } from "@visulima/fs"; 2import { join } from "node:path"; 3 4const collectFiles = async () => { 5 // Collect all .txt and .md files in /tmp/docs, up to 2 levels deep 6 const files = await collect(join("/tmp", "docs"), { 7 extensions: ["txt", "md"], 8 maxDepth: 2, 9 includeDirs: false, // Only collect files 10 }); 11 console.log(files); 12 // Example output: ['/tmp/docs/file1.txt', '/tmp/docs/subdir/report.md'] 13 14 // Collect all .js files, excluding anything in node_modules 15 const jsFiles = await collect(join("/tmp", "project"), { 16 extensions: ["js"], 17 skip: [/node_modules/], 18 }); 19 console.log(jsFiles); 20}; 21 22collectFiles();
1function collectSync(directory, options): string[];
Defined in: packages/fs/src/find/collect-sync.ts:33
Synchronously collects all file paths within a directory that match the specified criteria. By default, it searches for JavaScript and TypeScript file extensions.
string
The root directory to start collecting files from.
WalkOptions
= {}
Optional configuration to control the collection process. See WalkOptions.
string
[]
An array of absolute file paths.
1import { collectSync } from "@visulima/fs"; 2import { join } from "node:path"; 3 4// Collect all .txt and .md files in /tmp/docs, up to 2 levels deep 5const files = collectSync(join("/tmp", "docs"), { 6 extensions: ["txt", "md"], 7 maxDepth: 2, 8 includeDirs: false, // Only collect files 9}); 10console.log(files); 11// Example output: ['/tmp/docs/file1.txt', '/tmp/docs/subdir/report.md'] 12 13// Collect all .js files, excluding anything in node_modules 14const jsFiles = collectSync(join("/tmp", "project"), { 15 extensions: ["js"], 16 skip: [/node_modules/], 17}); 18console.log(jsFiles);
1function emptyDir(dir, options?): Promise<void>;
Defined in: packages/fs/src/remove/empty-dir.ts:38
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.
The path to the directory to empty.
string
| URL
RetryOptions
Optional configuration for the operation. See RetryOptions.
Promise
<void
>
A promise that resolves when the directory is empty.
1import { emptyDir } from "@visulima/fs"; 2import { join } from "node:path"; 3 4const clearTempDir = async () => { 5 try { 6 await emptyDir(join("/tmp", "my-app-temp")); 7 console.log("Temporary directory emptied or created."); 8 } catch (error) { 9 console.error("Failed to empty directory:", error); 10 } 11}; 12 13clearTempDir();
1function emptyDirSync(dir, options?): void;
Defined in: packages/fs/src/remove/empty-dir-sync.ts:33
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.
The path to the directory to empty.
string
| URL
RetryOptions
Optional configuration for the operation. See RetryOptions.
void
void
1import { emptyDirSync } from "@visulima/fs"; 2import { join } from "node:path"; 3 4try { 5 emptyDirSync(join("/tmp", "my-app-temp")); 6 console.log("Temporary directory emptied or created."); 7} catch (error) { 8 console.error("Failed to empty directory:", error); 9}
1function ensureDir(directory): Promise<void>;
Defined in: packages/fs/src/ensure/ensure-dir.ts:20
Ensures that the directory exists. If the directory structure does not exist, it is created. Like mkdir -p.
The path to the directory to ensure exists.
string
| URL
Promise
<void
>
1import ensureDir from "@visulima/fs/ensure/ensure-dir"; 2 3await ensureDir("/tmp/foo/bar/baz"); 4// Creates the directory structure /tmp/foo/bar/baz if it doesn't exist
1function ensureDirSync(directory): void;
Defined in: packages/fs/src/ensure/ensure-dir-sync.ts:20
Ensures that the directory exists. If the directory structure does not exist, it is created. Like mkdir -p.
The path to the directory to ensure exists.
string
| URL
void
1import ensureDirSync from "@visulima/fs/ensure/ensure-dir-sync"; 2 3ensureDirSync("/tmp/foo/bar/baz"); 4// Creates the directory structure /tmp/foo/bar/baz if it doesn't exist
1function ensureFile(filePath): Promise<void>;
Defined in: packages/fs/src/ensure/ensure-file.ts:37
Asynchronously ensures that a file exists. If the directory structure for the file does not exist, it is created. If the file already exists, it is not modified.
The path to the file. Can be a string or a URL object.
string
| URL
Promise
<void
>
A Promise that resolves when the file has been created or confirmed to exist.
Will throw an error if the path exists and is not a file.
Will throw an error if directory or file creation fails for reasons other than the path not existing initially.
1import { ensureFile } from "@visulima/fs"; 2 3(async () => { 4 try { 5 await ensureFile("path/to/my/file.txt"); 6 console.log("File ensured!"); 7 8 await ensureFile(new URL("file:///path/to/another/file.log")); 9 console.log("Another file ensured!"); 10 } catch (error) { 11 console.error("Failed to ensure file:", error); 12 } 13})();
1function ensureFileSync(filePath): void;
Defined in: packages/fs/src/ensure/ensure-file-sync.ts:24
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 NOT MODIFIED.
The path to the file to ensure exists.
string
| URL
void
1import { ensureFileSync } from "@visulima/fs"; 2 3ensureFileSync("/tmp/foo/bar/baz.txt"); 4// Creates the file /tmp/foo/bar/baz.txt and any missing parent directories if they don't exist
1function ensureLink(source, destination): Promise<void>;
Defined in: packages/fs/src/ensure/ensure-link.ts:25
Ensures that the hard link exists. If the directory structure does not exist, it is created.
The path to the source file or directory.
string
| URL
The path to the destination link.
string
| URL
Promise
<void
>
1import { ensureLink } from "@visulima/fs"; 2import { join } from "node:path"; 3 4// ensure the link /tmp/foo/bar-link.txt points to /tmp/foo/bar.txt 5await ensureLink(join("/tmp", "foo", "bar.txt"), join("/tmp", "foo", "bar-link.txt"));
1function ensureLinkSync(source, destination): void;
Defined in: packages/fs/src/ensure/ensure-link-sync.ts:25
Ensures that the hard link exists. If the directory structure does not exist, it is created.
The path to the source file or directory.
string
| URL
The path to the destination link.
string
| URL
void
1import { ensureLinkSync } from "@visulima/fs"; 2import { join } from "node:path"; 3 4// ensure the link /tmp/foo/bar-link.txt points to /tmp/foo/bar.txt 5ensureLinkSync(join("/tmp", "foo", "bar.txt"), join("/tmp", "foo", "bar-link.txt"));
1function ensureSymlink(
2 target,
3 linkName,
4type?): Promise<void>;
Defined in: packages/fs/src/ensure/ensure-symlink.ts:39
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.
the source file path
string
| URL
the destination link path
string
| URL
Type
the type of the symlink, or null to use automatic detection
Promise
<void
>
A void promise that resolves once the link exists.
1import { ensureSymlink } from "@visulima/fs"; 2import { join } from "node:path"; 3 4// Ensure a symlink /tmp/foo/link-to-bar.txt points to /tmp/foo/bar.txt 5await ensureSymlink(join("/tmp", "foo", "bar.txt"), join("/tmp", "foo", "link-to-bar.txt")); 6 7// Ensure a directory symlink /tmp/foo/link-to-baz-dir points to /tmp/foo/baz-dir 8await ensureSymlink(join("/tmp", "foo", "baz-dir"), join("/tmp", "foo", "link-to-baz-dir"), "dir");
1function ensureSymlinkSync(
2 target,
3 linkName,
4 type?): void;
Defined in: packages/fs/src/ensure/ensure-symlink-sync.ts:39
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.
the source file path
string
| URL
the destination link path
string
| URL
Type
the type of the symlink, or null to use automatic detection
void
A void.
1import { ensureSymlinkSync } from "@visulima/fs"; 2import { join } from "node:path"; 3 4// Ensure a symlink /tmp/foo/link-to-bar.txt points to /tmp/foo/bar.txt 5ensureSymlinkSync(join("/tmp", "foo", "bar.txt"), join("/tmp", "foo", "link-to-bar.txt")); 6 7// Ensure a directory symlink /tmp/foo/link-to-baz-dir points to /tmp/foo/baz-dir 8ensureSymlinkSync(join("/tmp", "foo", "baz-dir"), join("/tmp", "foo", "link-to-baz-dir"), "dir");
1function findUp(name, options): Promise<string>;
Defined in: packages/fs/src/find/find-up.ts:55
Asynchronously finds a file or directory by walking up parent directories.
The name(s) of the file or directory to find. Can be a string, an array of strings, or a function that returns a name or FIND_UP_STOP
.
FindUpOptions
= {}
Optional configuration for the search. See FindUpOptions.
Promise
<string
>
A promise that resolves to the absolute path of the first found file/directory, or undefined
if not found.
1import { findUp } from "@visulima/fs"; 2import { join } from "node:path"; 3 4const findProjectRoot = async () => { 5 // Find the closest package.json, starting from /tmp/foo/bar/baz 6 const projectRoot = await findUp("package.json", { 7 cwd: join("/tmp", "foo", "bar", "baz"), 8 type: "file", 9 }); 10 console.log(projectRoot); // e.g., /tmp/foo/package.json or undefined 11 12 // Find the closest .git directory or a README.md file 13 const gitDirOrReadme = await findUp([".git", "README.md"], { 14 cwd: join("/tmp", "foo", "bar"), 15 }); 16 console.log(gitDirOrReadme); 17 18 // Find using a custom function, stopping at /tmp 19 const customFound = await findUp( 20 (directory) => { 21 if (directory === join("/tmp", "foo")) { 22 return "found-it-here.txt"; // Pretend this file exists in /tmp/foo 23 } 24 return undefined; 25 }, 26 { 27 cwd: join("/tmp", "foo", "bar", "baz"), 28 stopAt: join("/tmp"), 29 } 30 ); 31 console.log(customFound); 32}; 33 34findProjectRoot();
1function findUpSync(name, options): string;
Defined in: packages/fs/src/find/find-up-sync.ts:51
Synchronously finds a file or directory by walking up parent directories.
The name(s) of the file or directory to find. Can be a string, an array of strings, or a function that returns a name or FIND_UP_STOP
.
FindUpOptions
= {}
Optional configuration for the search. See FindUpOptions.
string
The absolute path of the first found file/directory, or undefined
if not found.
1import { findUpSync } from "@visulima/fs"; 2import { join } from "node:path"; 3 4// Find the closest package.json, starting from /tmp/foo/bar/baz 5const projectRoot = findUpSync("package.json", { 6 cwd: join("/tmp", "foo", "bar", "baz"), 7 type: "file", 8}); 9console.log(projectRoot); // e.g., /tmp/foo/package.json or undefined 10 11// Find the closest .git directory or a README.md file 12const gitDirOrReadme = findUpSync([".git", "README.md"], { 13 cwd: join("/tmp", "foo", "bar"), 14}); 15console.log(gitDirOrReadme); 16 17// Find using a custom function, stopping at /tmp 18const customFound = findUpSync( 19 (directory) => { 20 if (directory === join("/tmp", "foo")) { 21 return "found-it-here.txt"; // Pretend this file exists in /tmp/foo 22 } 23 return undefined; 24 }, 25 { 26 cwd: join("/tmp", "foo", "bar", "baz"), 27 stopAt: join("/tmp"), 28 } 29); 30console.log(customFound);
1function isAccessible(path, mode?): Promise<boolean>;
Defined in: packages/fs/src/is-accessible.ts:36
Asynchronously tests a user's permissions for the file or directory specified by path.
Returns a Promise that resolves to true
if the accessibility check is successful, false
otherwise.
The path to the file or directory. Can be a string or a URL object.
string
| URL
number
The accessibility checks to perform. Defaults to F_OK
(check for existence).
Other possible values include R_OK
(check for read access), W_OK
(check for write access),
and X_OK
(check for execute/search access). Multiple modes can be combined using bitwise OR.
Promise
<boolean
>
A Promise that resolves to a boolean indicating if the path is accessible with the specified mode.
1import { isAccessible, F_OK, R_OK } from "@visulima/fs"; 2 3(async () => { 4 if (await isAccessible("myFile.txt")) { 5 console.log("myFile.txt exists"); 6 } 7 8 if (await isAccessible("myFile.txt", R_OK)) { 9 console.log("myFile.txt is readable"); 10 } 11 12 if (await isAccessible("myDirectory", F_OK | R_OK | W_OK)) { 13 console.log("myDirectory exists, is readable and writable"); 14 } 15})();
1function isAccessibleSync(path, mode?): boolean;
Defined in: packages/fs/src/is-accessible-sync.ts:9
Synchronously tests a user's permissions for the file or directory specified by path
.
If the accessibility check is successful, true
is returned. Otherwise, false
is returned.
string
| URL
number
boolean
true
if the accessibility check is successful, false
otherwise.
A path to a file or directory. If a URL is provided, it must use the file:
protocol.
The accessibility checks to perform. Default: F_OK
(tests for existence of the file).
Other possible values are R_OK
(tests for read permission), W_OK
(tests for write permission),
and X_OK
(tests for execute permissions). Multiple modes can be combined using bitwise OR.
1import { isAccessibleSync, F_OK, R_OK, W_OK } from "@visulima/fs"; 2import { writeFileSync, unlinkSync, chmodSync } from "node:fs"; 3import { join } from "node:path"; 4 5const filePath = join("temp-access-test.txt"); 6 7// Test for existence (default mode) 8writeFileSync(filePath, "content"); 9console.log(`File exists: ${isAccessibleSync(filePath)}`); // true 10unlinkSync(filePath); 11console.log(`File exists after delete: ${isAccessibleSync(filePath)}`); // false 12 13// Test for read and write permissions 14writeFileSync(filePath, "content"); 15chmodSync(filePath, 0o600); // Read/Write for owner 16console.log(`Readable: ${isAccessibleSync(filePath, R_OK)}`); // true 17console.log(`Writable: ${isAccessibleSync(filePath, W_OK)}`); // true 18console.log(`Readable & Writable: ${isAccessibleSync(filePath, R_OK | W_OK)}`); // true 19 20chmodSync(filePath, 0o400); // Read-only for owner 21console.log(`Readable (after chmod): ${isAccessibleSync(filePath, R_OK)}`); // true 22console.log(`Writable (after chmod): ${isAccessibleSync(filePath, W_OK)}`); // false 23 24unlinkSync(filePath); // Clean up 25 26// Example with URL 27writeFileSync(filePath, "content for URL test"); 28const fileUrl = new URL(`file://${join(process.cwd(), filePath)}`); 29console.log(`URL exists: ${isAccessibleSync(fileUrl)}`); // true 30unlinkSync(filePath);
1function move( 2 sourcePath, 3 destinationPath, 4options): Promise<void>;
Defined in: packages/fs/src/move/index.ts:35
Move a file asynchronously.
string
The file you want to move.
string
Where you want the file moved.
MoveOptions
= {}
Configuration options.
Promise
<void
>
A Promise
that resolves when the file has been moved.
import { move } from '@visulima/fs';
await move('source/test.png', 'destination/test.png');
console.log('The file has been moved');
1function moveSync(
2 sourcePath,
3 destinationPath,
4 options?): void;
Defined in: packages/fs/src/move/index.ts:61
Move a file synchronously.
string
The file you want to move.
string
Where you want the file moved.
Configuration options.
void
Nothing is returned.
import { moveSync } from '@visulima/fs';
moveSync('source/test.png', 'destination/test.png');
console.log('The file has been moved');
1function readFile<O>(path, options?): Promise<ContentType<O>>;
Defined in: packages/fs/src/read/read-file.ts:57
Asynchronously reads the entire contents of a file.
It can also decompress the file content if a compression
option is provided.
O
extends ReadFileOptions
<"brotli"
| "gzip"
| "none"
> = undefined
The type of the options object, extending ReadFileOptions.
The path to the file to read. Can be a file URL or a string path.
string
| URL
O
Optional configuration for reading the file. See ReadFileOptions.
Available compression
methods: "brotli", "gzip", "none" (default).
Promise
<ContentType
<O
>>
A promise that resolves with the file content. The type of the content (string or Buffer)
depends on the buffer
option (defaults to string if buffer
is false or not set).
1import { readFile } from "@visulima/fs"; 2import { join } from "node:path"; 3 4const readMyFile = async () => { 5 try { 6 // Read a regular text file 7 const content = await readFile(join("path", "to", "my-file.txt")); 8 console.log("File content:", content); 9 10 // Read a file as a Buffer 11 const bufferContent = await readFile(join("path", "to", "another-file.bin"), { buffer: true }); 12 console.log("Buffer length:", bufferContent.length); 13 14 // Read and decompress a gzipped file 15 // Assume my-archive.txt.gz exists 16 // const decompressedContent = await readFile(join("path", "to", "my-archive.txt.gz"), { compression: "gzip", encoding: "utf8" }); 17 // console.log("Decompressed content:", decompressedContent); 18 } catch (error) { 19 console.error("Failed to read file:", error); 20 } 21}; 22 23readMyFile();
1function readFileSync<O>(path, options?): ContentType<O>;
Defined in: packages/fs/src/read/read-file-sync.ts:51
Synchronously reads the entire contents of a file.
It can also decompress the file content if a compression
option is provided.
O
extends ReadFileOptions
<"brotli"
| "gzip"
| "none"
> = undefined
The type of the options object, extending ReadFileOptions.
The path to the file to read. Can be a file URL or a string path.
string
| URL
O
Optional configuration for reading the file. See ReadFileOptions.
Available compression
methods: "brotli", "gzip", "none" (default).
ContentType
<O
>
The file content. The type of the content (string or Buffer)
depends on the buffer
option (defaults to string if buffer
is false or not set).
1import { readFileSync } from "@visulima/fs"; 2import { join } from "node:path"; 3 4try { 5 // Read a regular text file 6 const content = readFileSync(join("path", "to", "my-file.txt")); 7 console.log("File content:", content); 8 9 // Read a file as a Buffer 10 const bufferContent = readFileSync(join("path", "to", "another-file.bin"), { buffer: true }); 11 console.log("Buffer length:", bufferContent.length); 12 13 // Read and decompress a gzipped file 14 // Assume my-archive.txt.gz exists 15 // const decompressedContent = readFileSync(join("path", "to", "my-archive.txt.gz"), { compression: "gzip", encoding: "utf8" }); 16 // console.log("Decompressed content:", decompressedContent); 17} catch (error) { 18 console.error("Failed to read file:", error); 19}
Asynchronously reads a JSON file and then parses it into an object.
The expected type of the parsed JSON object.
The path to the JSON file to read. Can be a file URL or a string path.
A function to transform the results. This function is called for each member of the object.
Alternatively, this can be the options
object if no reviver function is provided.
Optional configuration for reading and parsing the JSON file. See ReadJsonOptions.
If reviver
is an object, this argument is ignored.
1import { readJson } from "@visulima/fs"; 2import { join } from "node:path"; 3 4const readMyJson = async () => { 5 try { 6 const data = await readJson(join("path", "to", "my-config.json")); 7 console.log("Config data:", data); 8 9 // With a reviver function 10 const dataWithReviver = await readJson(join("path", "to", "another.json"), (key, value) => { 11 if (key === "date") return new Da
No vulnerabilities found.