UNPKG

@visulima/fs

Version:

Human friendly file system utilities for Node.js

2,656 lines (1,622 loc) 139 kB
<div align="center"> <h3>Visulima fs</h3> <p> Human friendly file system utilities for Node.js </p> </div> <br /> <div align="center"> [![typescript-image]][typescript-url] [![npm-image]][npm-url] [![license-image]][license-url] </div> --- <div align="center"> <p> <sup> Daniel Bannert's open source work is supported by the community on <a href="https://github.com/sponsors/prisis">GitHub Sponsors</a> </sup> </p> </div> --- ## Install ```sh npm install @visulima/fs ``` ```sh yarn add @visulima/fs ``` ```sh pnpm add @visulima/fs ``` > **Note:** If you want to parse or write YAML, you'll need to install `yaml` as well. ```sh npm install yaml ``` ```sh yarn add yaml ``` ```sh pnpm add yaml ``` > After installing `yaml`, you can use the `readYaml`, `readYamlSync` and `writeYaml`, `writeYamlSync` functions from `@visulima/fs/yaml`. ## Usage ## walk ```typescript import { walk } from "@visulima/fs"; const filesAndFolders: string[] = []; for await (const index of walk(`${__dirname}/fixtures`, {})) { filesAndFolders.push(index.path); } console.log(filesAndFolders); ``` ## walkSync ```typescript 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](<https://en.wikipedia.org/wiki/Glob_(programming)>) 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](<https://en.wikipedia.org/wiki/Glob_(programming)>) 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. ```typescript import { findUp } from "@visulima/fs"; // Returns a Promise for the found path or undefined if it could not be found. const file = await findUp("package.json"); console.log(file); ``` ## findUpSync Find a file or directory by walking up parent directories. ```typescript import { findUpSync } from "@visulima/fs"; // Returns the found path or undefined if it could not be found. 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. ```typescript import { readFile } from "@visulima/fs"; // Returns a Promise for the file contents. const file = await readFile("package.json"); console.log(file); ``` ## readFileSync Read a file. ```typescript import { readFileSync } from "@visulima/fs"; // Returns the file contents. 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. ```typescript import { isAccessible } from "@visulima/fs"; // Returns a Promise for the result. const file = await isAccessible("package.json"); console.log(file); ``` ## isAccessibleSync Check if a file or directory exists and is accessible. ```typescript import { isAccessibleSync } from "@visulima/fs"; // Returns the result. 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. ```typescript import { parseJson, JSONError } from "@visulima/fs/utils"; const json = '{\n\t"foo": true,\n}'; JSON.parse(json); /* undefined:3 } ^ SyntaxError: Unexpected token } */ parseJson(json); /* JSONError: Unexpected token } in JSON at position 16 while parsing near '{ "foo": true,}' 1 | { 2 | "foo": true, > 3 | } | ^ */ parseJson(json, "foo.json"); /* JSONError: Unexpected token } in JSON at position 16 while parsing near '{ "foo": true,}' in foo.json 1 | { 2 | "foo": true, > 3 | } | ^ */ ``` ### 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter) 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 <!-- TYPEDOC --> # eol ## Functions ### detect() ```ts function detect(content): "\n" | "\r\n"; ``` Defined in: [packages/fs/src/eol.ts:29](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/eol.ts#L29) Detect the EOL character for string input. Returns null if no newline. #### Parameters ##### content `string` The string content to detect the EOL from. #### Returns "\n" \| "\r\n" #### Example ```javascript import { detect } from "@visulima/fs/eol"; detect("Hello\r\nWorld"); // "\r\n" detect("Hello\nWorld"); // "\n" detect("HelloWorld"); // null ``` --- ### format() ```ts function format(content, eol): string; ``` Defined in: [packages/fs/src/eol.ts:54](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/eol.ts#L54) Format the file to the targeted EOL. #### Parameters ##### content `string` The string content to format. ##### eol The target EOL character. "\n" | "\r\n" #### Returns `string` #### Example ```javascript import { format, LF, CRLF } from "@visulima/fs/eol"; format("Hello\r\nWorld\nUnix", LF); // "Hello\nWorld\nUnix" format("Hello\nWorld\r\nWindows", CRLF); // "Hello\r\nWorld\r\nWindows" ``` ## Variables ### CRLF ```ts const CRLF: "\r\n"; ``` Defined in: [packages/fs/src/eol.ts:9](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/eol.ts#L9) End-of-line character for Windows platforms. --- ### EOL ```ts const EOL: "\n" | "\r\n"; ``` Defined in: [packages/fs/src/eol.ts:14](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/eol.ts#L14) End-of-line character evaluated for the current platform. --- ### LF ```ts const LF: "\n"; ``` Defined in: [packages/fs/src/eol.ts:6](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/eol.ts#L6) End-of-line character for POSIX platforms such as macOS and Linux. # error ## Classes ### AlreadyExistsError Defined in: [packages/fs/src/error/already-exists-error.ts:28](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/already-exists-error.ts#L28) Error thrown when a file or directory already exists at a specified path, and an operation was expecting it not to. #### Example ```javascript import { AlreadyExistsError } from "@visulima/fs/error"; // Assuming it's exported from an index or directly import { ensureSymlinkSync } from "@visulima/fs"; // Or any function that might throw this import { join } from "node:path"; try { // Example: ensureSymlinkSync might throw this if a file (not a symlink) already exists at linkName // For demonstration, let's assume someFunction internally throws it: const someFunctionThatMightThrow = (path) => { if (path === "/tmp/existing-file.txt") { // Simulate a check throw new AlreadyExistsError(`file already exists at '/tmp/existing-file.txt'`); } }; someFunctionThatMightThrow("/tmp/existing-file.txt"); } catch (error) { if (error instanceof AlreadyExistsError) { console.error(`Operation failed because path exists: ${error.message}`); console.error(`Error code: ${error.code}`); // EEXIST } else { console.error("An unexpected error occurred:", error); } } ``` #### Extends - `Error` #### Constructors ##### Constructor ```ts new AlreadyExistsError(message): AlreadyExistsError; ``` Defined in: [packages/fs/src/error/already-exists-error.ts:33](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/already-exists-error.ts#L33) Creates a new instance. ###### Parameters ###### message `string` The error message. ###### Returns [`AlreadyExistsError`](#alreadyexistserror) ###### Overrides ```ts Error.constructor; ``` #### Accessors ##### code ###### Get Signature ```ts get code(): string; ``` Defined in: [packages/fs/src/error/already-exists-error.ts:38](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/already-exists-error.ts#L38) ###### Returns `string` ###### Set Signature ```ts set code(_name): void; ``` Defined in: [packages/fs/src/error/already-exists-error.ts:43](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/already-exists-error.ts#L43) ###### Parameters ###### \_name `string` ###### Returns `void` ##### name ###### Get Signature ```ts get name(): string; ``` Defined in: [packages/fs/src/error/already-exists-error.ts:48](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/already-exists-error.ts#L48) ###### Returns `string` ###### Set Signature ```ts set name(_name): void; ``` Defined in: [packages/fs/src/error/already-exists-error.ts:53](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/already-exists-error.ts#L53) ###### Parameters ###### \_name `string` ###### Returns `void` ###### Overrides ```ts Error.name; ``` #### Methods ##### captureStackTrace() ```ts static 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 ###### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ###### Returns `void` ###### Inherited from ```ts Error.captureStackTrace; ``` #### Properties ##### cause? ```ts optional cause: unknown; ``` Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es2022.error.d.ts:26 ###### Inherited from ```ts Error.cause; ``` ##### message ```ts message: string; ``` Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1077 ###### Inherited from ```ts Error.message; ``` ##### stack? ```ts optional stack: string; ``` Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1078 ###### Inherited from ```ts Error.stack; ``` ##### prepareStackTrace()? ```ts static 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 ###### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ###### Returns `any` ###### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ###### Inherited from ```ts Error.prepareStackTrace; ``` ##### stackTraceLimit ```ts static stackTraceLimit: number; ``` Defined in: node_modules/.pnpm/@types+node@18.19.71/node_modules/@types/node/globals.d.ts:100 ###### Inherited from ```ts Error.stackTraceLimit; ``` --- ### DirectoryError Defined in: [packages/fs/src/error/directory-error.ts:36](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/directory-error.ts#L36) 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. #### Example ```javascript import { DirectoryError } from "@visulima/fs/error"; import { readFile } from "@visulima/fs"; // Or any function that might throw this import { join } from "node:path"; const attemptToReadFileFromDir = async () => { try { // Attempting to read a directory as if it were a file // This is a conceptual example; readFile might throw a different error first // depending on its internal checks, but EISDIR is the underlying system error. // Forcing the scenario: const pretendReadFileOnDir = (path) => { if (path === "/tmp/my-directory") { // Simulate a directory path throw new DirectoryError(`read '/tmp/my-directory'`); } }; pretendReadFileOnDir("/tmp/my-directory"); // await readFile(join("/tmp", "my-directory")); } catch (error) { if (error instanceof DirectoryError) { console.error(`Operation failed, path is a directory: ${error.message}`); console.error(`Error code: ${error.code}`); // EISDIR } else { console.error("An unexpected error occurred:", error); } } }; attemptToReadFileFromDir(); ``` #### Extends - `Error` #### Constructors ##### Constructor ```ts new DirectoryError(message): DirectoryError; ``` Defined in: [packages/fs/src/error/directory-error.ts:41](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/directory-error.ts#L41) Creates a new instance. ###### Parameters ###### message `string` The error message. ###### Returns [`DirectoryError`](#directoryerror) ###### Overrides ```ts Error.constructor; ``` #### Accessors ##### code ###### Get Signature ```ts get code(): string; ``` Defined in: [packages/fs/src/error/directory-error.ts:46](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/directory-error.ts#L46) ###### Returns `string` ###### Set Signature ```ts set code(_name): void; ``` Defined in: [packages/fs/src/error/directory-error.ts:51](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/directory-error.ts#L51) ###### Parameters ###### \_name `string` ###### Returns `void` ##### name ###### Get Signature ```ts get name(): string; ``` Defined in: [packages/fs/src/error/directory-error.ts:56](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/directory-error.ts#L56) ###### Returns `string` ###### Set Signature ```ts set name(_name): void; ``` Defined in: [packages/fs/src/error/directory-error.ts:61](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/directory-error.ts#L61) ###### Parameters ###### \_name `string` ###### Returns `void` ###### Overrides ```ts Error.name; ``` #### Methods ##### captureStackTrace() ```ts static 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 ###### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ###### Returns `void` ###### Inherited from ```ts Error.captureStackTrace; ``` #### Properties ##### cause? ```ts optional cause: unknown; ``` Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es2022.error.d.ts:26 ###### Inherited from ```ts Error.cause; ``` ##### message ```ts message: string; ``` Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1077 ###### Inherited from ```ts Error.message; ``` ##### stack? ```ts optional stack: string; ``` Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1078 ###### Inherited from ```ts Error.stack; ``` ##### prepareStackTrace()? ```ts static 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 ###### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ###### Returns `any` ###### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ###### Inherited from ```ts Error.prepareStackTrace; ``` ##### stackTraceLimit ```ts static stackTraceLimit: number; ``` Defined in: node_modules/.pnpm/@types+node@18.19.71/node_modules/@types/node/globals.d.ts:100 ###### Inherited from ```ts Error.stackTraceLimit; ``` --- ### NotEmptyError Defined in: [packages/fs/src/error/not-empty-error.ts:40](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/not-empty-error.ts#L40) Error thrown when a directory is not empty. #### Example ```javascript import { NotEmptyError } from "@visulima/fs/error"; import { rmdir } from "node:fs/promises"; // Or any fs function that might throw this system error import { join } from "node:path"; const attemptToRemoveNonEmptyDir = async () => { const dirPath = join("/tmp", "my-non-empty-dir"); // Assume this directory exists and has files try { // Forcing the scenario for demonstration, as rmdir might throw its own specific error. // Node.js fs operations that encounter a non-empty directory when expecting an empty one // typically throw an error with code ENOTEMPTY. const simulateNotEmpty = (path) => { if (path === dirPath) { // Simulate check for non-empty throw new NotEmptyError(`rmdir '${dirPath}'`); } }; simulateNotEmpty(dirPath); // await rmdir(dirPath); // This would likely throw an error with code ENOTEMPTY } catch (error) { if (error instanceof NotEmptyError) { console.error(`Operation failed, directory is not empty: ${error.message}`); console.error(`Error code: ${error.code}`); // ENOTEMPTY } else { console.error("An unexpected error occurred:", error); } } }; // You would need to set up a non-empty directory at /tmp/my-non-empty-dir for a real test // import { ensureDirSync, writeFileSync } from "@visulima/fs"; // ensureDirSync(dirPath); // writeFileSync(join(dirPath, "somefile.txt"), "content"); attemptToRemoveNonEmptyDir(); ``` #### Extends - `Error` #### Constructors ##### Constructor ```ts new NotEmptyError(message): NotEmptyError; ``` Defined in: [packages/fs/src/error/not-empty-error.ts:45](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/not-empty-error.ts#L45) Creates a new instance. ###### Parameters ###### message `string` The error message. ###### Returns [`NotEmptyError`](#notemptyerror) ###### Overrides ```ts Error.constructor; ``` #### Accessors ##### code ###### Get Signature ```ts get code(): string; ``` Defined in: [packages/fs/src/error/not-empty-error.ts:50](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/not-empty-error.ts#L50) ###### Returns `string` ###### Set Signature ```ts set code(_name): void; ``` Defined in: [packages/fs/src/error/not-empty-error.ts:55](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/not-empty-error.ts#L55) ###### Parameters ###### \_name `string` ###### Returns `void` ##### name ###### Get Signature ```ts get name(): string; ``` Defined in: [packages/fs/src/error/not-empty-error.ts:60](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/not-empty-error.ts#L60) ###### Returns `string` ###### Set Signature ```ts set name(_name): void; ``` Defined in: [packages/fs/src/error/not-empty-error.ts:65](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/not-empty-error.ts#L65) ###### Parameters ###### \_name `string` ###### Returns `void` ###### Overrides ```ts Error.name; ``` #### Methods ##### captureStackTrace() ```ts static 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 ###### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ###### Returns `void` ###### Inherited from ```ts Error.captureStackTrace; ``` #### Properties ##### cause? ```ts optional cause: unknown; ``` Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es2022.error.d.ts:26 ###### Inherited from ```ts Error.cause; ``` ##### message ```ts message: string; ``` Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1077 ###### Inherited from ```ts Error.message; ``` ##### stack? ```ts optional stack: string; ``` Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1078 ###### Inherited from ```ts Error.stack; ``` ##### prepareStackTrace()? ```ts static 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 ###### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ###### Returns `any` ###### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ###### Inherited from ```ts Error.prepareStackTrace; ``` ##### stackTraceLimit ```ts static stackTraceLimit: number; ``` Defined in: node_modules/.pnpm/@types+node@18.19.71/node_modules/@types/node/globals.d.ts:100 ###### Inherited from ```ts Error.stackTraceLimit; ``` --- ### NotFoundError Defined in: [packages/fs/src/error/not-found-error.ts:33](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/not-found-error.ts#L33) Error thrown when a file or directory is not found at a specified path. #### Example ```javascript import { NotFoundError } from "@visulima/fs/error"; import { readFile } from "@visulima/fs"; // Or any function that might throw this import { join } from "node:path"; const tryReadingNonExistentFile = async () => { const filePath = join("/tmp", "this-file-does-not-exist.txt"); try { // Forcing the scenario for demonstration, as readFile itself would throw this. const simulateNotFound = (path) => { if (path === filePath) { throw new NotFoundError(`no such file or directory, open '${filePath}'`); } }; simulateNotFound(filePath); // await readFile(filePath); } catch (error) { if (error instanceof NotFoundError) { console.error(`Operation failed, path not found: ${error.message}`); console.error(`Error code: ${error.code}`); // ENOENT } else { console.error("An unexpected error occurred:", error); } } }; tryReadingNonExistentFile(); ``` #### Extends - `Error` #### Constructors ##### Constructor ```ts new NotFoundError(message): NotFoundError; ``` Defined in: [packages/fs/src/error/not-found-error.ts:38](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/not-found-error.ts#L38) Creates a new instance. ###### Parameters ###### message `string` The error message. ###### Returns [`NotFoundError`](#notfounderror) ###### Overrides ```ts Error.constructor; ``` #### Accessors ##### code ###### Get Signature ```ts get code(): string; ``` Defined in: [packages/fs/src/error/not-found-error.ts:43](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/not-found-error.ts#L43) ###### Returns `string` ###### Set Signature ```ts set code(_name): void; ``` Defined in: [packages/fs/src/error/not-found-error.ts:48](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/not-found-error.ts#L48) ###### Parameters ###### \_name `string` ###### Returns `void` ##### name ###### Get Signature ```ts get name(): string; ``` Defined in: [packages/fs/src/error/not-found-error.ts:53](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/not-found-error.ts#L53) ###### Returns `string` ###### Set Signature ```ts set name(_name): void; ``` Defined in: [packages/fs/src/error/not-found-error.ts:58](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/not-found-error.ts#L58) ###### Parameters ###### \_name `string` ###### Returns `void` ###### Overrides ```ts Error.name; ``` #### Methods ##### captureStackTrace() ```ts static 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 ###### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ###### Returns `void` ###### Inherited from ```ts Error.captureStackTrace; ``` #### Properties ##### cause? ```ts optional cause: unknown; ``` Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es2022.error.d.ts:26 ###### Inherited from ```ts Error.cause; ``` ##### message ```ts message: string; ``` Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1077 ###### Inherited from ```ts Error.message; ``` ##### stack? ```ts optional stack: string; ``` Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1078 ###### Inherited from ```ts Error.stack; ``` ##### prepareStackTrace()? ```ts static 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 ###### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ###### Returns `any` ###### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ###### Inherited from ```ts Error.prepareStackTrace; ``` ##### stackTraceLimit ```ts static stackTraceLimit: number; ``` Defined in: node_modules/.pnpm/@types+node@18.19.71/node_modules/@types/node/globals.d.ts:100 ###### Inherited from ```ts Error.stackTraceLimit; ``` --- ### PermissionError Defined in: [packages/fs/src/error/permission-error.ts:34](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/permission-error.ts#L34) Error thrown when an operation is not permitted due to insufficient privileges or other access control restrictions. #### Example ```javascript import { PermissionError } from "@visulima/fs/error"; import { writeFile } from "@visulima/fs"; // Or any function that might throw this import { join } from "node:path"; const tryWritingToProtectedFile = async () => { const filePath = join("/root", "protected-file.txt"); // A path that typically requires root privileges try { // Forcing the scenario for demonstration, as writeFile itself would throw this. const simulatePermissionError = (path) => { if (path === filePath) { throw new PermissionError(`open '${filePath}'`); } }; simulatePermissionError(filePath); // await writeFile(filePath, "test content"); } catch (error) { if (error instanceof PermissionError) { console.error(`Operation not permitted: ${error.message}`); console.error(`Error code: ${error.code}`); // EPERM } else { console.error("An unexpected error occurred:", error); } } }; tryWritingToProtectedFile(); ``` #### Extends - `Error` #### Constructors ##### Constructor ```ts new PermissionError(message): PermissionError; ``` Defined in: [packages/fs/src/error/permission-error.ts:39](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/permission-error.ts#L39) Creates a new instance. ###### Parameters ###### message `string` The error message. ###### Returns [`PermissionError`](#permissionerror) ###### Overrides ```ts Error.constructor; ``` #### Accessors ##### code ###### Get Signature ```ts get code(): string; ``` Defined in: [packages/fs/src/error/permission-error.ts:44](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/permission-error.ts#L44) ###### Returns `string` ###### Set Signature ```ts set code(_name): void; ``` Defined in: [packages/fs/src/error/permission-error.ts:49](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/permission-error.ts#L49) ###### Parameters ###### \_name `string` ###### Returns `void` ##### name ###### Get Signature ```ts get name(): string; ``` Defined in: [packages/fs/src/error/permission-error.ts:54](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/permission-error.ts#L54) ###### Returns `string` ###### Set Signature ```ts set name(_name): void; ``` Defined in: [packages/fs/src/error/permission-error.ts:59](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/permission-error.ts#L59) ###### Parameters ###### \_name `string` ###### Returns `void` ###### Overrides ```ts Error.name; ``` #### Methods ##### captureStackTrace() ```ts static 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 ###### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ###### Returns `void` ###### Inherited from ```ts Error.captureStackTrace; ``` #### Properties ##### cause? ```ts optional cause: unknown; ``` Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es2022.error.d.ts:26 ###### Inherited from ```ts Error.cause; ``` ##### message ```ts message: string; ``` Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1077 ###### Inherited from ```ts Error.message; ``` ##### stack? ```ts optional stack: string; ``` Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1078 ###### Inherited from ```ts Error.stack; ``` ##### prepareStackTrace()? ```ts static 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 ###### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ###### Returns `any` ###### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ###### Inherited from ```ts Error.prepareStackTrace; ``` ##### stackTraceLimit ```ts static stackTraceLimit: number; ``` Defined in: node_modules/.pnpm/@types+node@18.19.71/node_modules/@types/node/globals.d.ts:100 ###### Inherited from ```ts Error.stackTraceLimit; ``` --- ### WalkError Defined in: [packages/fs/src/error/walk-error.ts:43](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/walk-error.ts#L43) Error thrown in walk or walkSync during iteration. #### Example ```javascript import { WalkError } from "@visulima/fs/error"; import { walk } from "@visulima/fs"; import { join } from "node:path"; const processDirectory = async () => { const dirToWalk = join("/tmp", "non-existent-or-permission-denied-dir"); try { // Forcing the scenario: walk might throw a WalkError if it encounters an issue // like a directory it cannot read during the walk process. const simulateWalkError = async (rootDir) => { // Let's say readdir inside walk fails for a subdirectory. const underlyingError = new Error("Permission denied reading subdirectory"); throw new WalkError(underlyingError, rootDir); }; // This is conceptual. In a real scenario, 'walk' itself would throw. // for await (const entry of walk(dirToWalk)) { // console.log(entry.path); // } await simulateWalkError(dirToWalk); } catch (error) { if (error instanceof WalkError) { console.error(`Error during directory walk of "${error.root}": ${error.message}`); if (error.cause) { console.error(`Underlying cause: ${error.cause}`); } } else { console.error("An unexpected error occurred:", error); } } }; processDirectory(); ``` #### Extends - `Error` #### Constructors ##### Constructor ```ts new WalkError(cause, root): WalkError; ``` Defined in: [packages/fs/src/error/walk-error.ts:52](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/walk-error.ts#L52) Constructs a new instance. ###### Parameters ###### cause `unknown` The underlying error or reason for the walk failure. ###### root `string` The root directory path where the walk operation started or encountered the error. ###### Returns [`WalkError`](#walkerror) ###### Overrides ```ts Error.constructor; ``` #### Accessors ##### name ###### Get Signature ```ts get name(): string; ``` Defined in: [packages/fs/src/error/walk-error.ts:61](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/walk-error.ts#L61) ###### Returns `string` ###### Set Signature ```ts set name(_name): void; ``` Defined in: [packages/fs/src/error/walk-error.ts:66](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/walk-error.ts#L66) ###### Parameters ###### \_name `string` ###### Returns `void` ###### Overrides ```ts Error.name; ``` #### Methods ##### captureStackTrace() ```ts static 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 ###### Parameters ###### targetObject `object` ###### constructorOpt? `Function` ###### Returns `void` ###### Inherited from ```ts Error.captureStackTrace; ``` #### Properties ##### cause? ```ts optional cause: unknown; ``` Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es2022.error.d.ts:26 ###### Inherited from ```ts Error.cause; ``` ##### message ```ts message: string; ``` Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1077 ###### Inherited from ```ts Error.message; ``` ##### root ```ts root: string; ``` Defined in: [packages/fs/src/error/walk-error.ts:45](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/error/walk-error.ts#L45) File path of the root that's being walked. ##### stack? ```ts optional stack: string; ``` Defined in: node_modules/.pnpm/typescript@5.8.3/node_modules/typescript/lib/lib.es5.d.ts:1078 ###### Inherited from ```ts Error.stack; ``` ##### prepareStackTrace()? ```ts static 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 ###### Parameters ###### err `Error` ###### stackTraces `CallSite`[] ###### Returns `any` ###### See https://v8.dev/docs/stack-trace-api#customizing-stack-traces ###### Inherited from ```ts Error.prepareStackTrace; ``` ##### stackTraceLimit ```ts static stackTraceLimit: number; ``` Defined in: node_modules/.pnpm/@types+node@18.19.71/node_modules/@types/node/globals.d.ts:100 ###### Inherited from ```ts Error.stackTraceLimit; ``` ## References ### JSONError Re-exports [JSONError](utils.md#jsonerror) # index ## Functions ### collect() ```ts function collect(directory, options): Promise<string[]>; ``` Defined in: [packages/fs/src/find/collect.ts:37](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/find/collect.ts#L37) Asynchronously collects all file paths within a directory that match the specified criteria. By default, it searches for JavaScript and TypeScript file extensions. #### Parameters ##### directory `string` The root directory to start collecting files from. ##### options [`WalkOptions`](#walkoptions) = `{}` Optional configuration to control the collection process. See [WalkOptions](#walkoptions). #### Returns `Promise`\<`string`[]\> A promise that resolves to an array of absolute file paths. #### Example ```javascript import { collect } from "@visulima/fs"; import { join } from "node:path"; const collectFiles = async () => { // Collect all .txt and .md files in /tmp/docs, up to 2 levels deep const files = await collect(join("/tmp", "docs"), { extensions: ["txt", "md"], maxDepth: 2, includeDirs: false, // Only collect files }); console.log(files); // Example output: ['/tmp/docs/file1.txt', '/tmp/docs/subdir/report.md'] // Collect all .js files, excluding anything in node_modules const jsFiles = await collect(join("/tmp", "project"), { extensions: ["js"], skip: [/node_modules/], }); console.log(jsFiles); }; collectFiles(); ``` --- ### collectSync() ```ts function collectSync(directory, options): string[]; ``` Defined in: [packages/fs/src/find/collect-sync.ts:33](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/find/collect-sync.ts#L33) Synchronously collects all file paths within a directory that match the specified criteria. By default, it searches for JavaScript and TypeScript file extensions. #### Parameters ##### directory `string` The root directory to start collecting files from. ##### options [`WalkOptions`](#walkoptions) = `{}` Optional configuration to control the collection process. See [WalkOptions](#walkoptions). #### Returns `string`[] An array of absolute file paths. #### Example ```javascript import { collectSync } from "@visulima/fs"; import { join } from "node:path"; // Collect all .txt and .md files in /tmp/docs, up to 2 levels deep const files = collectSync(join("/tmp", "docs"), { extensions: ["txt", "md"], maxDepth: 2, includeDirs: false, // Only collect files }); console.log(files); // Example output: ['/tmp/docs/file1.txt', '/tmp/docs/subdir/report.md'] // Collect all .js files, excluding anything in node_modules const jsFiles = collectSync(join("/tmp", "project"), { extensions: ["js"], skip: [/node_modules/], }); console.log(jsFiles); ``` --- ### emptyDir() ```ts function emptyDir(dir, options?): Promise<void>; ``` Defined in: [packages/fs/src/remove/empty-dir.ts:38](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/remove/empty-dir.ts#L38) 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 The path to the directory to empty. `string` | `URL` ##### options? `RetryOptions` Optional configuration for the operation. See RetryOptions. #### Returns `Promise`\<`void`\> A promise that resolves when the directory is empty. #### Example ```javascript import { emptyDir } from "@visulima/fs"; import { join } from "node:path"; const clearTempDir = async () => { try { await emptyDir(join("/tmp", "my-app-temp")); console.log("Temporary directory emptied or created."); } catch (error) { console.error("Failed to empty directory:", error); } }; clearTempDir(); ``` --- ### emptyDirSync() ```ts function emptyDirSync(dir, options?): void; ``` Defined in: [packages/fs/src/remove/empty-dir-sync.ts:33](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/remove/empty-dir-sync.ts#L33) 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 The path to the directory to empty. `string` | `URL` ##### options? `RetryOptions` Optional configuration for the operation. See RetryOptions. #### Returns `void` void #### Example ```javascript import { emptyDirSync } from "@visulima/fs"; import { join } from "node:path"; try { emptyDirSync(join("/tmp", "my-app-temp")); console.log("Temporary directory emptied or created."); } catch (error) { console.error("Failed to empty directory:", error); } ``` --- ### ensureDir() ```ts function ensureDir(directory): Promise<void>; ``` Defined in: [packages/fs/src/ensure/ensure-dir.ts:20](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/ensure/ensure-dir.ts#L20) Ensures that the directory exists. If the directory structure does not exist, it is created. Like mkdir -p. #### Parameters ##### directory The path to the directory to ensure exists. `string` | `URL` #### Returns `Promise`\<`void`\> #### Example ```javascript import ensureDir from "@visulima/fs/ensure/ensure-dir"; await ensureDir("/tmp/foo/bar/baz"); // Creates the directory structure /tmp/foo/bar/baz if it doesn't exist ``` --- ### ensureDirSync() ```ts function ensureDirSync(directory): void; ``` Defined in: [packages/fs/src/ensure/ensure-dir-sync.ts:20](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/ensure/ensure-dir-sync.ts#L20) Ensures that the directory exists. If the directory structure does not exist, it is created. Like mkdir -p. #### Parameters ##### directory The path to the directory to ensure exists. `string` | `URL` #### Returns `void` #### Example ```javascript import ensureDirSync from "@visulima/fs/ensure/ensure-dir-sync"; ensureDirSync("/tmp/foo/bar/baz"); // Creates the directory structure /tmp/foo/bar/baz if it doesn't exist ``` --- ### ensureFile() ```ts function ensureFile(filePath): Promise<void>; ``` Defined in: [packages/fs/src/ensure/ensure-file.ts:37](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/ensure/ensure-file.ts#L37) 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. #### Parameters ##### filePath The path to the file. Can be a string or a URL object. `string` | `URL` #### Returns `Promise`\<`void`\> A Promise that resolves when the file has been created or confirmed to exist. #### Throws Will throw an error if the path exists and is not a file. #### Throws Will throw an error if directory or file creation fails for reasons other than the path not existing initially. #### Example ```typescript import { ensureFile } from "@visulima/fs"; (async () => { try { await ensureFile("path/to/my/file.txt"); console.log("File ensured!"); await ensureFile(new URL("file:///path/to/another/file.log")); console.log("Another file ensured!"); } catch (error) { console.error("Failed to ensure file:", error); } })(); ``` --- ### ensureFileSync() ```ts function ensureFileSync(filePath): void; ``` Defined in: [packages/fs/src/ensure/ensure-file-sync.ts:24](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/ensure/ensure-file-sync.ts#L24) 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. #### Parameters ##### filePath The path to the file to ensure exists. `string` | `URL` #### Returns `void` #### Example ```javascript import { ensureFileSync } from "@visulima/fs"; ensureFileSync("/tmp/foo/bar/baz.txt"); // Creates the file /tmp/foo/bar/baz.txt and any missing parent directories if they don't exist ``` --- ### ensureLink() ```ts function ensureLink(source, destination): Promise<void>; ``` Defined in: [packages/fs/src/ensure/ensure-link.ts:25](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/ensure/ensure-link.ts#L25) Ensures that the hard link exists. If the directory structure does not exist, it is created. #### Parameters ##### source The path to the source file or directory. `string` | `URL` ##### destination The path to the destination link. `string` | `URL` #### Returns `Promise`\<`void`\> #### Example ```javascript import { ensureLink } from "@visulima/fs"; import { join } from "node:path"; // ensure the link /tmp/foo/bar-link.txt points to /tmp/foo/bar.txt await ensureLink(join("/tmp", "foo", "bar.txt"), join("/tmp", "foo", "bar-link.txt")); ``` --- ### ensureLinkSync() ```ts function ensureLinkSync(source, destination): void; ``` Defined in: [packages/fs/src/ensure/ensure-link-sync.ts:25](https://github.com/visulima/visulima/blob/07f43a001a4f33a3ebcce9072d404a8975539608/packages/fs/src/ensure/ensure-link-sync.ts#L25) Ensures that the hard link exists. If the directory structure does not exist, it is created. #### Parameters ##### source The path to the source file or directory. `string` | `URL` ##### destination The path to the destination link. `string` | `URL` #### Returns `void` #### Example ```javascript import { ensureLinkSync } from "@visulima/fs"; import { join } from "node:path"; // ensure the link /tmp/foo/bar-link.txt points to /tmp/foo/bar.txt ensureLinkSync(join("/tmp", "foo", "bar.txt"), join("/tmp", "foo", "bar-link.txt")); ``` --- ### ensureSymlink() ```ts function ensureSymlink(target, linkName, type?): Promise<void>; ``` Defined in: [packages/fs/src/ensure/ensure-symlink.ts:39](https://github.com/visulima/visulima