Class default

A wrapper class representing a filepath on which operations can be performed.

Example

Here are a few examples of how the Path class instantiates:

// Assume that the current working directory is:
"/home/jsmith/Documents/Work" on Unix and
"C:\\Users\\JSmith\\Documents\\Work" on Windows
const fp1 = new Path("~")
const fp2 = new Path(".")
const fp3 = new Path("..")
const fp4_unix = new Path("/users/hsimpson/Documents")
const fp4_win = new Path("C:\\Users\\HSimpson\\Documents")
const fp5 = new Path("./foo")
const fp6 = new Path("../bar")
const fp7 = new Path("/")
console.log([fp1.path, fp2.path, fp3.path, fp4_unix.path, fp4_win.path,
fp5.path, fp6.path, fp7.path
].join("\n"));

// For a Unix user:
>>>
/home/jsmith
/home/jsmith/Documents/Work
/home/jsmith/Documents
/users/hsimpson/Documents
// Windows example has been omitted
/home/jsmith/Documents/Work/foo
/home/jsmith/Documents/bar
/

// For a Windows user:
>>>
C:/Users/JSmith
C:/Users/JSmith/Documents/Work
C:/Users/JSmith/Documents
// Unix example has been omitted
C:/Users/HSimpson/Documents
C:/Users/JSmith/Documents/Work/foo
C:/Users/JSmith/Documents/bar
C:/

Hierarchy

  • default

Constructors

Properties

basename: string

The basename of a filepath.

Example

  • For a filepath of /foo/bar/baz.txt, the basename is baz.txt.
  • For a filepath of /foo/bar, the basename is bar.
descriptor: null | number

The number that uniquely identifies a filepath in the operating system it resides. This is null while the filepath is closed and a number when the filepath is in an open state.

dirname: string

The portion of the filepath other than the basename.

Example

  • For a filepath of /home/jsmith/Documents/Work/foo.txt, the dirname is /home/jsmith/Documents/Work.
  • For a filepath of C:\\Users\\JSmith\\Documents, the dirname is C:\\Users\\JSmith.
ext: string

The final extension in the filepath.

⚠️ In this library, the leading dot is included as part of the extension. ⚠️

Example

  • For a filepath of /foo/bar/baz.txt, the extension is .txt.
  • For a filepath of /foo/bar/baz, the extension is an empty string.
  • For a filepath of /foo/bar/baz.tar.gz, the extension is .gz.
path: string

The full filepath represented by this Path instance.

root: string

The root directory of the filepath.

Remarks

⚠️ In this library, the normalization process of the filepath results in the root being always expressed with forward slashes. (i.e. C:/ instead of C:\). Windows users may find this more difficult to work with; they are advised to use the class's toString(true) method for respecting the backslash representation. ⚠️

@examples

  • For a Unix filepath of /foo/bar/baz, the root directory is /.
  • For a Windows filepath of C:\foo\bar\baz, the root directory is C: (expressed as C:/ in this library).
stem: string

The portion of the basename without the extension.

Example

  • For a filepath of /foo/bar/baz.txt, the stem is baz.
  • For a filepath of /foo/bar/baz, the stem is baz.
suffixes: string[]

An array of strings representing the individual extensions found at the end of the filepath.

⚠️In this library, the leading dot is included for each extension in the array.⚠️

Example

const fp1 = new Path("/home/jsmith/Documents/foo.txt");
const fp2 = new Path("/home/jsmith/Documents/bar.tar.gz");
const fp3 = new Path("/home/jsmith/Documents/baz");
console.log(fp1.suffixes);
>>> [ '.txt' ]
console.log(fp2.suffixes);
>>> [ '.tar', '.gz' ]
console.log(fp3.suffixes);
>>> []

Methods

  • Asynchronously tests a user's permissions for the underling filepath.

    Returns

    If mode was specified, a boolean reflecting the permissions. Otherwise, returns an Object with keys "canRead", "canWrite", "canExecute" and values as a boolean of whether permissions for that operation are available.

    Parameters

    • mode: number

      the permissions to check for. Use fs.constants variables as input, NOT octal numbers. Defaults to undefined, resulting in checking for read, write, and execute permissions.

    Returns Promise<boolean>

  • Parameters

    • Optional mode: undefined

    Returns Promise<AccessResult>

  • Synchronously tests a user's permissions for the underling filepath.

    Returns

    If mode was specified, a boolean reflecting the permissions. Otherwise, returns an Object with keys "canRead", "canWrite", "canExecute" and values as a boolean of whether permissions for that operation are available.

    Parameters

    • Optional mode: number

      the permissions to check for. Use fs.constants variables as input, NOT octal numbers. Defaults to undefined, resulting in checking for read, write, and execute permissions.

    Returns boolean

  • Parameters

    • Optional mode: undefined

    Returns AccessResult

  • Alias of the join() method. Appends strings to the end of the underlying filepath, creating a new Path instance.

    ⚠️ Note that ".." and "." are treated literally and will not be resolved. For appending file segments with resolving behavior use the resolve() method. ⚠️

    Returns

    A new Path instance with the strings appended.

    Parameters

    • Rest ...segments: string[]

      Strings which should be appended to the Path instance in order to create a new one.

    Returns default

  • Asynchronously changes the permissions of the underlying filepath.

    • Caveats: on Windows only the write permission can be changed, and the distinction among the permissions of group, owner or others is not implemented.

    Returns

    Returns the Path instance that called this method.

    Parameters

    • mode: string | number

      A string (i.e. fs.constants) or octal number (ex. 0o511) representation of the new filepath permissions.

    Returns Promise<default>

  • Synchronously changes the permissions of the underlying filepath.

    • Caveats: on Windows only the write permission can be changed, and the distinction among the permissions of group, owner or others is not implemented.

    Returns

    Returns the Path instance that called this method.

    Parameters

    • mode: string | number

      A string (i.e. fs.constants) or octal number (ex. 0o511) representation of the new filepath permissions.

    Returns default

  • Asynchronously changes the ownership of the underlying filepath.

    Returns

    Returns the Path instance that called this method.

    Parameters

    • uid: number

      User id.

    • gid: number

      Group id.

    Returns Promise<default>

  • Synchronously changes the ownership of the underlying filepath.

    Returns

    Returns the Path instance that called this method.

    Parameters

    • uid: number

      User id.

    • gid: number

      Group id.

    Returns default

  • Asynchronously determines whether a directory contains a given child filepath or basename.

    Returns

    The located child as a Path instance or false if no child path could be found.

    Example

    // In fp there exists a file called "foo.txt"
    const fp = new Path("/home/jsmith/Documents");
    const usingBasename = await fp.containsImmediateChild("foo.txt");
    const usingFullPath = await fp.containsImmediateChild("/home/jsmith/Documents/foo.txt");
    const usingPathInst = await fp.containsImmediateChild(fp.join("foo.txt"));
    usingBasename && console.log(usingBasename.path);
    >>> /home/jsmith/Documents/foo.txt
    usingFullPath && console.log(usingFullPath.path);
    >>> /home/jsmith/Documents/foo.txt
    usingPathInst && console.log(usingPathInst.path);
    >>> /home/jsmith/Documents/foo.txt
    console.log(await fp.containsImmediateChild("bar.json"));
    >>> false

    Parameters

    • child: string | default

      The child filepath to look for within the underlying filepath. The following are accepted:

      • The basename of the child filepath as a string
      • The fullpath of the child filepath as a string
      • A Path instance of the child filepath

    Returns Promise<false | default>

  • Synchronously determines whether a directory contains a given child filepath or basename.

    Returns

    The located child as a Path instance or false if no child path could be found.

    Example

    // In fp there exists a file called "foo.txt"
    const fp = new Path("/home/jsmith/Documents");
    const usingBasename = fp.containsImmediateChildSync("foo.txt");
    const usingFullPath = fp.containsImmediateChildSync("/home/jsmith/Documents/foo.txt");
    const usingPathInst = fp.containsImmediateChildSync(fp.join("foo.txt"));
    usingBasename && console.log(usingBasename.path);
    >>> /home/jsmith/Documents/foo.txt
    usingFullPath && console.log(usingFullPath.path);
    >>> /home/jsmith/Documents/foo.txt
    usingPathInst && console.log(usingPathInst.path);
    >>> /home/jsmith/Documents/foo.txt
    console.log(fp.containsImmediateChildSync("bar.json"));
    >>> false

    Parameters

    • child: string | default

      The child filepath to look for within the underlying filepath. The following are accepted:

      • The basename of the child filepath as a string
      • The fullpath of the child filepath as a string
      • A Path instance of the child filepath

    Returns false | default

  • Asynchronously copies the underlying filepath to the indicated destination.

    Parameters

    • dst: string | default

      The filepath destination to where the underlying path should be copied.

      • If the instance is a directory, the children of the directory will be copied to this location.
      • If the instance is a file, it itself will be copied to the new location.
    • Optional options: CopyOptions

      CopyOptions By default:

      • overwrite is set to true
      • errorOnExist is set to false
      • dereference is set to `false
      • preserveTimestamps is set to false
      • interRelativeSource is set to undefined (relative paths will be resolved relative to the current working directory)

    Returns Promise<default>

  • Synchronously copies the underlying filepath to the indicated destination.

    Parameters

    • dst: string | default

      The filepath destination to where the underlying path should be copied.

      • If the instance is a directory, the children of the directory will be copied to this location.
      • If the instance is a file, it itself will be copied to the new location.
    • Optional options: CopyOptionsSync

      CopyOptions By default:

      • overwrite is set to true
      • errorOnExist is set to false
      • dereference is set to `false
      • preserveTimestamps is set to false
      • interRelativeSource is set to undefined (relative paths will be resolved relative to the current working directory)

    Returns default

  • Alias for remove(). Asynchronously deletes the underlying filepath.

    Returns Promise<void>

  • Alias for removeSync(). Synchronously deletes the underlying filepath.

    Returns void

  • Asynchronously checks whether the underlying filepath exists.

    Returns

    A boolean of whether the filepath exists or not.

    Returns Promise<boolean>

  • Synchronously checks whether the underlying filepath exists.

    Returns

    A boolean of whether the filepath exists or not.

    Returns boolean

  • Retrieves filepaths located exactly N levels away from the underlying filepath. Utilizes globbing under the hood, thereby requiring glob options.

    Returns

    Depends on the asIterator parameter:

    • if true, returns an AsyncIterator of Path instances
    • if false, returns an Array of Path instances

    Parameters

    • depth: number

      The depth to retrieve filepaths from. Interpretation is as follows:

      • If greater than or equal to 1, will retrieve child/grandchild/etc. paths.
      • If equal to 0, will retrieve the current filepath and its siblings.
      • If less than 0, will retrieve parent/grandparent/etc paths.
    • Optional asIterator: true

      Whether the result should be an AsyncIterator of Path instances instead of an Array of them. Defaults to false.

    • Optional options: GlobOptions

      Options governing the underlying globbing behavior that is used to retrieve the filepaths. Is based off fast-glob's options. By default, the following options are set if no options are provided:

      • onlyFiles: false
      • onlyDirectories: false
      • dot: false (filepaths with basenames starting with a dot are ignored)

    Returns Promise<AsyncGenerator<default, void, unknown>>

  • Parameters

    • depth: number
    • Optional asIterator: false
    • Optional options: GlobOptions

    Returns Promise<default[]>

  • Asynchronously globs for filepaths stemming from the Path instance.

    Returns

    An Array of globbed Path instances.

    Parameters

    • patterns: string | string[]

      A string or collection of strings representing glob patterns to search.

    • Optional options: GlobOptions

      fast-glob options. By default:

      • objectMode is set to false and enforced
      • stats is set to false and enforced
      • onlyDirectories is set to false
      • onlyFiles is set to false
      • dot is set to false

    Returns Promise<default[]>

  • Asynchronously glob for filepaths stemming from the Path instance while yielding them instead of returning an immediate array.

    Yields

    Path instances.

    Parameters

    • patterns: string | string[]

      A string or collection of strings representing glob patterns to search.

    • Optional options: GlobOptions

      fast-glob options. By default:

      • objectMode is set to false and enforced
      • stats is set to false and enforced
      • onlyDirectories is set to false
      • onlyFiles is set to false
      • dot is set to false

    Returns AsyncGenerator<default, void, unknown>

  • Synchronously globs for filepaths stemming from the Path instance.

    Returns

    An Array of globbed Path instances.

    Parameters

    • patterns: string | string[]

      A string or collection of strings representing glob patterns to search.

    • Optional options: GlobOptions

      fast-glob options. By default:

      • objectMode is set to false and enforced
      • stats is set to false and enforced
      • onlyDirectories is set to false
      • onlyFiles is set to false
      • dot is set to false

    Returns default[]

  • Asynchronously checks whether the filepath is a directory.

    Returns

    A boolean of whether this is a directory or not.

    Returns Promise<boolean>

  • Synchronously checks whether the filepath is a directory.

    Returns

    A boolean of whether this is a directory or not.

    Returns boolean

  • Asynchronously checks whether the filepath is a first-in-first-out queue.

    Returns

    A boolean of whether this is a first-in-first-out queue or not.

    Returns Promise<boolean>

  • Synchronously checks whether the filepath is a first-in-first-out queue.

    Returns

    A boolean of whether this is a first-in-first-out queue or not.

    Returns boolean

  • Asynchronously checks whether the filepath is a file.

    Returns

    A boolean of whether this is a file or not.

    Returns Promise<boolean>

  • Synchronously checks whether the filepath is a file.

    Returns

    A boolean of whether this is a file or not.

    Returns boolean

  • Asynchronously checks whether the filepath is a socket.

    Returns

    A boolean of whether this is a socket or not.

    Returns Promise<boolean>

  • Synchronously checks whether the filepath is a socket.

    Returns

    A boolean of whether this is a socket or not.

    Returns boolean

  • Asynchronously checks whether the filepath is a symlink.

    Returns

    A boolean of whether this is a symlink or not.

    Returns Promise<boolean>

  • Synchronously checks whether the filepath is a symlink.

    Returns

    A boolean of whether this is a symlink or not.

    Returns boolean

  • Appends strings to the end of the underlying filepath, creating a new Path instance.

    ⚠️ Note that ".." and "." are treated literally and will not be resolved. For appending file segments with resolving behavior use the resolve() method. ⚠️

    Returns

    A new Path instance with the strings appended.

    Example

    const fp = new Path("/home/jsmith/Documents");
    console.log(fp.join("foo", "bar").path);
    console.log(fp.join("..", "baz").path);
    >>> "/home/jsmith/Documents/foo/bar"
    >>> "/home/jsmith/Documents/../baz"

    Parameters

    • Rest ...segments: string[]

      Strings which should be appended to the Path instance in order to create a new one.

    Returns default

  • Asynchronously creates a new directory, including intermediate parental components.

    Returns

    Returns false if throwErrOnFail is false and an error is encountered while making the directory path. Otherwise, returns the Path instance that called this method.

    Parameters

    • mode: number = 0o777

      An octal number (ex. 0o511) representing of the new filepath permissions to impart. Defaults to 0o777.

    • throwErrOnFail: boolean = false

      Whether to rethrow any generated error. Defaults to false.

    Returns Promise<false | default>

  • Synchronously creates a new directory, including intermediate parental components.

    Returns

    Returns false if throwErrOnFail is false and an error is encountered while making the directory path. Otherwise, returns the Path instance that called this method.

    Parameters

    • mode: number = 0o777

      An octal number (ex. 0o511) representing of the new filepath permissions to impart. Defaults to 0o777.

    • throwErrOnFail: boolean = false

      Whether to rethrow any generated error. Defaults to false.

    Returns false | default

  • Asynchronously creates a new file, including intermediate parental components.

    Returns

    Returns false if throwErrOnFail is false and an error is encountered while making the file path. Otherwise, returns the Path instance that called this method.

    Parameters

    • throwErrOnFail: boolean = false

      Whether to rethrow any generated error. Defaults to false.

    Returns Promise<false | default>

  • Synchronously creates a new file, including intermediate parental components.

    Returns

    Returns false if throwErrOnFail is false and an error is encountered while making the file path. Otherwise, returns the Path instance that called this method.

    Parameters

    • throwErrOnFail: boolean = false

      Whether to rethrow any generated error. Defaults to false.

    Returns false | default

  • Asynchronously creates a symlink. Either:

    • links the underlying filepath to a target symlink that is created (default) OR
    • has a the underlying filepath interpreted as the symlink to be created when linking to some target path.

    Returns

    The filepath outlined in target as a Path instance.

    Parameters

    • target: string | default

      The corresponding target filepath that a symlink should be made to OR that is a symlink linking to the underlying filepath.

    • Optional options: SymlinkOptions

      SymlinkOptions controlling the operation of this function. By default:

      • targetIsLink is true (the path in the target parameter is assumed to be the symlink to be made)
      • type is undefined(on Windows, the type of symlink to make will be inferred)
      • interpRelativeSource is "cwd", meaning that a relative target string will be resolved relative to the current working directory.

    Returns Promise<default>

  • Synchronously creates a symlink. Either:

    • links the underlying filepath to a target symlink that is created (default) OR
    • has a the underlying filepath interpreted as the symlink to be created when linking to some target path.

    Returns

    The filepath outlined in target as a Path instance.

    Parameters

    • target: string | default

      The corresponding target filepath that a symlink should be made to OR that is a symlink linking to the underlying filepath.

    • Optional options: SymlinkOptions

      SymlinkOptions controlling the operation of this function. By default:

      • targetIsLink is true (the path in the target parameter is assumed to be the symlink to be made)
      • type is undefined(on Windows, the type of symlink to make will be inferred)
      • interpRelativeSource is "cwd", meaning that a relative target string will be resolved relative to the current working directory.

    Returns default

  • Asynchronously moves the underlying filepath to the indicated destination.

    Returns

    Returns the destination filepath as a Path instance.

    Parameters

    • dst: string | default

      The filepath destination to where the underlying path should be moved.

      • If the instance is a directory, the children of the directory will be moved to this location.
      • If the instance is a file, it itself will be moved to the new location.
    • Optional options: MoveOptions

      MoveOptions By default:

      • overwrite is set to true
      • interRelativeSource is set to undefined (relative paths will be resolved relative to the current working directory)

    Returns Promise<default>

  • Synchronously moves the underlying filepath to the indicated destination.

    Returns

    Returns the destination filepath as a Path instance.

    Parameters

    • dst: string | default

      The filepath destination to where the underlying path should be moved.

      • If the instance is a directory, the children of the directory will be moved to this location.
      • If the instance is a file, it itself will be moved to the new location.
    • Optional options: MoveOptions

      MoveOptions By default:

      • overwrite is set to true
      • interRelativeSource is set to undefined (relative paths will be resolved relative to the current working directory)

    Returns default

  • Asynchronously opens a file and returns its file descriptor.

    Returns

    The numeric file descriptor.

    Parameters

    Returns Promise<number>

  • Retrieves the parent directory or an earlier ancestor filepath.

    Returns

    The parent or higher ancestor (i.e grandparent) directory of this filepath as a Path instance.

    Example

    const fp = new Path("/home/jsmith/Documents/foo.txt");
    console.log(fp.parent(0).path); // Returns the same path
    >>> "/home/jsmith/Documents/foo.txt"
    console.log(fp.parent(1).path); // Returns the immediate parent
    >>> "/home/jsmith/Documents"
    console.log(fp.parent(2).path); // Returns the grandparent
    >>> "/home/jsmith"
    console.log(fp.parent(3).path);
    >>> "/home"
    console.log(fp.parent(4).path);
    >>> "/"
    console.log(fp.parent(5).path);
    >>> "/"
    console.log(fp.parent(9001).path); // Exceeding root, the root is returned
    >>> "/"
    console.log(fp.parent(-9001).path); // Negative numbers return the same path
    >>> "/home/jsmith/Documents/foo.txt"

    Parameters

    • Optional numIncrements: number

      The number of directory levels to ascend.

      • If this number exceeds number of ascentions required to reach the root directory, then the root directory itself is returned.
      • If this number is equal to or less than 0, it will return a copy of the current Path.

      Defaults to undefined, meaning that the immediate parent directory is returned.

    Returns default

  • Splits the underlying filepath into its individual components.

    Returns

    An Array of the strings comprising the Path instance.

    Example

    const fp = new Path("/home/jsmith/Documents")
    console.log(fp.parts())
    >>> [ '/', 'home', 'jsmith', 'Documents' ]

    Returns string[]

  • Asynchronously reads a portion of the data from the underlying file.

    Returns

    An object with the properties of buffer, which is the updated buffer, and bytesRead, which is the number of bytes that were read from the file.

    Parameters

    • buffer: ArrayBufferView

      The Buffer that the data will be written to.

    • offset: number

      The position in buffer to write the data to.

    • length: number

      The number of bytes to read.

    • position: null | number

      Specifies where to begin reading from in the file. If position is null or -1 , data will be read from the current file position, and the file position will be updated. If position is an integer, the file position will be unchanged.

    • closeAfterwards: boolean = true

      Whether to close the file after the operation completes. Defaults to true.

    • Optional openOptions: OpenFileOptions

    Returns Promise<{ fileDescriptor: null | number }>

  • Asynchronously collects the children of a directory path.

    Returns

    An Array of Path instances that are children of the current instance.

    Returns Promise<default[]>

  • Asynchronously yields child filepaths.

    Yields

    A child Path instance.

    Returns AsyncGenerator<default, void, unknown>

  • Synchronously yields child filepaths.

    Yields

    A child Path instance.

    Returns Generator<default, void, unknown>

  • Synchronously collects the children of a directory path.

    Returns

    An Array of Path instances that are children of the current instance.

    Returns default[]

  • Asynchronously parses data coming from a file.

    Returns

    The contents of the file either as a decoded string or as a Buffer if no encoding was provided.

    Parameters

    • options: { encoding: BufferEncoding; flag?: string }
      • encoding: BufferEncoding
      • Optional flag?: string

    Returns Promise<string>

  • Parameters

    • encoding: BufferEncoding

    Returns Promise<string>

  • Returns Promise<Buffer>

  • Synchronously parses data coming from a file.

    Returns

    The contents of the file either as a decoded string or as a Buffer if no encoding was provided.

    Parameters

    • options: { encoding: BufferEncoding; flag?: string }
      • encoding: BufferEncoding
      • Optional flag?: string

    Returns string

  • Parameters

    • encoding: BufferEncoding

    Returns string

  • Returns Buffer

  • Asynchronously reads in the underlying filepath JSON file and parses it into a JSON object.

    Returns

    A JSON object.

    Parameters

    • Optional options: string | ReadOptions

    Returns Promise<JSONObject>

  • Synchronously reads in the underlying filepath JSON file and parses it into a JSON object.

    Returns

    A JSON object.

    Parameters

    • Optional options: string | ReadOptions

    Returns any

  • Asynchronously retrieves the filepath that the underlying symlink is pointing to.

    Returns

    A Path instance of the target.

    Example

    // symFP points to /home/jsmith/Documents
    const sympFP = new Path("/home/jsmith/ExampleSymlink.symlink")
    const origPath = (await symFP.readLink()).path
    console.log(origPath)
    >>> "/home/jsmith/Documents"

    Returns Promise<default>

  • Synchronously retrieves the filepath that the underlying symlink is pointing to.

    Returns

    A Path instance of the target.

    Example

    // symFP points to /home/jsmith/Documents
    const sympFP = new Path("/home/jsmith/ExampleSymlink.symlink")
    const origPath = symFP.readLinkSync().path
    console.log(origPath)
    >>> "/home/jsmith/Documents"

    Returns default

  • Synchronously reads a portion of the data from the underlying file.

    Returns

    The number of bytes read.

    Parameters

    • buffer: ArrayBufferView

      The Buffer that the data will be written to.

    • offset: number

      The position in buffer to write the data to.

    • length: number

      The number of bytes to read.

    • position: null | number

      Specifies where to begin reading from in the file.

    • closeAfterwards: boolean = true

      Whether to close the file after the operation completes. Defaults to true. If position is null or -1 , data will be read from the current file position, and the file position will be updated. If position is an integer, the file position will be unchanged.

    • Optional openOptions: OpenFileOptions

    Returns { bytesRead: number; fileDescriptor: null | number }

    • bytesRead: number
    • fileDescriptor: null | number
  • Depicts the relative path from the Path instance to another filepath.

    Returns

    A string representation of the relative path.

    Example

    const fp = new Path("/home/jsmith/Documents")
    console.log(fp.relative("/home"))
    >>> "../.."

    Parameters

    • to: string | default

      The filepath that this instance should be compared against.

    • useSystemPathDelimiter: boolean = false

      Whether to present the final string in accordance with the operating system's filepath delimiter. Default is false.

    Returns string

  • Asynchronously deletes the underlying filepath.

    Returns Promise<void>

  • Synchronously deletes the underlying filepath.

    Returns void

  • Resolves a sequence of path segments into a new absolute Path from the underlying path. Respects ".." and will increment directories accordingly.

    ⚠️ Note that strings beginning with a single "." will be treated as if the dot character does not exist. Use the join() method as an alternative for treating ".." and "." as literal. ⚠️

    Returns

    The resolved Path instance.

    Example

    const fp = new Path("/home/jsmith/Documents")
    console.log(fp.resolve("../Downloads").path)
    >>> "/home/jsmith/Downloads"

    Parameters

    • Rest ...segments: string[]

      An Array of strings respresenting path segments to append and resolve to the underlying path.

    Returns default

  • Alias for this.parts(). Splits the underlying filepath into its individual components.

    Returns

    An Array of the strings comprising the Path instance.

    Returns string[]

  • Asynchronously retrieves the stat object for the filepath.

    Returns

    The Stats object for the underlying filepath.

    Returns Promise<Stats>

  • Synchronously retrieves the stat object for the filepath.

    Returns

    The Stats object for the underlying filepath.

    Returns Stats

  • Depicts an Object version of the Path instance.

    Returns

    An Object representation of the underlying filepath; PathJSON.

    Parameters

    • useSystemPathDelimiter: boolean = false

      Whether to respect the system-specific filepath delimiter. Defaults to false.

    Returns PathJSON

  • Depicts a string version of the Path instance.

    Returns

    A string representation of the underlying filepath.

    Parameters

    • useSystemPathDelimiter: boolean = false

      Whether to respect the system-specific filepath delimiter. Defaults to false.

    Returns string

  • Asynchronously traverses the tree structure of the directory system, starting from the current instances as the root and returns a nested Object representation of the tree structure. Each branching of the tree is comprised of an object with two properties: "filepath", which is the Path instance of the filepath at that location, and "children" which is either null in the case of a non-directory or an Array of more branch objects.

    Returns

    A representation of the filepath tree structure.

    Parameters

    • Optional asString: true

      Whether to convert the "filepath" property automatically to a string representation of the path instead.

    • Optional useSystemPathDelimiter: boolean

    Returns Promise<treeBranch<string>>

  • Parameters

    • Optional asString: false
    • Optional useSystemPathDelimiter: boolean

    Returns Promise<treeBranch<default>>

  • Synchronously traverses the tree structure of the directory system, starting from the current instances as the root and returns a nested Object representation of the tree structure. Each branching of the tree is comprised of an object with two properties: "filepath", which is the Path instance of the filepath at that location, and "children" which is either null in the case of a non-directory or an Array of more branch objects.

    Returns

    A representation of the filepath tree structure.

    Parameters

    • Optional asString: true

      Whether to convert the "filepath" property automatically to a string representation of the path instead.

    • Optional useSystemPathDelimiter: boolean

    Returns treeBranch<string>

  • Parameters

    • Optional asString: false
    • Optional useSystemPathDelimiter: boolean

    Returns treeBranch<default>

  • Alias for remove(). Asynchronously deletes the underlying filepath.

    Returns Promise<void>

  • Alias for removeSync(). Synchronously deletes the underlying filepath.

    Returns void

  • Asynchronously traverses the tree structure of the directory system, starting from the current instance as the root and allows for callbacks to occur for each encountered filepath.

    Parameters

    • Optional callback: ((fp: default, ...args: unknown[]) => void)

      A callback function for each encountered Path. Its first argument must accept a Path instance.

        • (fp: default, ...args: unknown[]): void
        • Parameters

          • fp: default
          • Rest ...args: unknown[]

          Returns void

    Returns Promise<void>

  • Synchronously traverses the tree structure of the directory system, starting from the current instance as the root and allows for callbacks to occur for each encountered filepath.

    Parameters

    • Optional callback: ((fp: default, ...args: unknown[]) => void)

      A callback function for each encountered Path. Its first argument must accept a Path instance.

        • (fp: default, ...args: unknown[]): void
        • Parameters

          • fp: default
          • Rest ...args: unknown[]

          Returns void

    Returns void

  • Wrapper around implementing a Chokidar watcher on the underlying filepath.

    Returns

    Either a PathWatcher instance (default) or a Promise that resolves to a PathWatcher instance if waitUntilReady is true.

    Parameters

    • Optional options: WatchOptions

      Chokidar options controlling the behavior of the filepath watcher.

    • Optional waitUntilReady: false

      Whether to defer the return of the watcher until its "ready" event has been emitted. Defaults to undefined (will not wait for the ready event).

    Returns PathWatcher

  • Parameters

    • Optional options: WatchOptions
    • Optional waitUntilReady: true

    Returns Promise<PathWatcher>

  • Creates a new Path instance with a replaced basename.

    Returns

    A new Path instance featuring the replacement basename.

    Example

    const fp = new Path("/home/jsmith/Documents/foo.txt")
    console.log(fp.withBasename("bar.json").path)
    >>> "/home/jsmith/Documents/bar.json"

    Parameters

    • name: string

      The new basename to replace the existing one.

    Returns default

  • Creates a new Path instance with a replaced last extension.

    ⚠️ If a suffix contains multiple components (i.e. .tar.gz) and the entirety of the suffix is desired to be replaced, use this.withSuffix(). ⚠️

    Returns

    A new Path instance featuring the replacement last extension.

    Example

    const fp1 = new Path("/home/mpasternak/Documents/foo.tar.gz");
    console.log(fp1.withExtension("qui").path);
    console.log(fp1.withExtension("").path);
    >>> "/home/mpasternak/Documents/foo.tar.qui"
    >>> "/home/mpasternak/Documents/foo.tar"

    const fp2 = new Path("/home/mpasternak/Documents/bar.txt");
    console.log(fp2.withExtension(".json").path);
    console.log(fp2.withExtension("").path);
    >>> "/home/mpasternak/Documents/bar.json"
    >>> "/home/mpasternak/Documents/bar"

    Parameters

    • ext: string

      The new extension to replace the existing one.

    Returns default

  • Creates a new Path instance with a replaced stem.

    Returns

    A new Path instance featuring the replacement stem.

    const fp = new Path("/home/jsmith/Documents/foo.txt")
    console.log(fp.withStem("bar").path)
    >>> "/home/jsmith/Documents/bar.txt"

    Parameters

    • stem: string

      The new stem to replace the existing one.

    Returns default

  • Creates a new Path instance with a replaced set of suffix extensions.

    Returns

    A new Path instance featuring the replaced suffix(es).

    Example

    const fp = new Path("/home/mpasternak/Documents/foo.tar.gz");

    console.log(fp.withSuffix(["bar", "baz"]).path);
    >>> "/home/mpasternak/Documents/foo.bar.baz"

    console.log(fp.withSuffix("qui").path);
    >>> "/home/mpasternak/Documents/foo.qui"

    console.log(fp.withSuffix("").path);
    >>> "/home/mpasternak/Documents/foo"

    Parameters

    • suffix: string | string[]

      The new suffix to replace the existing one. Behavior patterns are as follows:

      • If provided an Array of strings, it will concatenate each with a "." character before appending to the existing stem.
      • If provided a non-blank string, it will overwite everything after the first "." in the current basename.
      • If a blank string is provided, then all extensions will be removed.

    Returns default

  • Asynchronously writes buffer-like data into the underlying file.

    Type Parameters

    Type Parameters

    • TBuffer extends TypedArray | DataView

    Parameters

    • buffer: TBuffer

      the Buffer which should be written into the underlying file.

    • Optional offset: number

      The position in the buffer from which to begin writing

    • Optional length: number

      The number of bytes to write.

    • Optional position: null | number

      Specifies where to begin writing into the file.

    • closeAfterwards: boolean = true

      Whether to close the file after the operation completes. Defaults to true.

    • Optional openOptions: OpenFileOptions

    Returns Promise<{ fileDescriptor: null | number }>

  • Asynchronously writes data to the underlying filepath.

    Returns

    Returns the Path instance that called this method

    Parameters

    • data: string | Buffer | Uint8Array

      The data to write to the file.

    • Optional options: WriteFileOptions

    Returns Promise<default>

  • Synchronously writes data to the underlying filepath.

    Returns

    Returns the Path instance that called this method

    Parameters

    • data: string | Buffer | Uint8Array

      The data to write to the file.

    • Optional options: WriteFileOptions

    Returns default

  • Asynchronously write a JSON-compatible object to a .json file.

    Returns

    Returns the Path instance which called this method.

    Parameters

    • data: JSONObject

      A JSON-compatible object to write into the file.

    • Optional options: WriteOptions

    Returns Promise<default>

  • Synchronously write a JSON-compatible object to a .json file.

    Returns

    Returns the Path instance which called this method.

    Parameters

    • data: JSONObject

      A JSON-compatible object to write into the file.

    • Optional options: WriteOptions

    Returns default

  • Synchronously writes buffer-like data into the underlying file.

    Type Parameters

    Type Parameters

    • TBuffer extends TypedArray | DataView

    Parameters

    • buffer: TBuffer

      the Buffer which should be written into the underlying file.

    • Optional offset: number

      The position in the buffer from which to begin writing

    • Optional length: number

      The number of bytes to write.

    • Optional position: null | number

      Specifies where to begin writing into the file.

    • closeAfterwards: boolean = true

      Whether to close the file after the operation completes. Defaults to true.

    • Optional openOptions: OpenFileOptions

    Returns { bytesWritten: number; fileDescriptor: null | number }

    • bytesWritten: number
    • fileDescriptor: null | number
  • Converts the PATH variable into an Array of Path instances.

    Returns

    An Array of Path instances of the filepaths recorded in PATH.

    Returns default[]

  • Parses the mode of a filepath into a more understandable octal-like representation (i.e. 777 for full-permissions)

    Returns

    A 3-digit representation of the permissions indicated by the provided mode.

    Example

    console.log(Path.parseModeIntoOctal(16877))
    >>> 755

    Parameters

    • mode: number | Stats

      The mode of a filepath, as received from fs.Stats or the fs.Stats object itself

    Returns number

  • Joins filepaths to create a single string representation, delimited by the system-specific environment delimiter.

    Returns

    Filepaths concatenated by the system-specific environment delimiter.

    Parameters

    • Rest ...paths: (string | default)[]

      A collection of strings or Path instances to be joined together using the system-specific environment delimiter (":" vs ";"). Useful for converting a collection of filepaths into a single string to be set as an environment variable.

    Returns string

Generated using TypeDoc