The basename of a filepath.
/foo/bar/baz.txt, the basename is baz.txt./foo/bar, the basename is bar.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.
The portion of the filepath other than the basename.
/home/jsmith/Documents/Work/foo.txt, the dirname is /home/jsmith/Documents/Work.C:\\Users\\JSmith\\Documents, the dirname is C:\\Users\\JSmith.The final extension in the filepath.
⚠️ In this library, the leading dot is included as part of the extension. ⚠️
/foo/bar/baz.txt, the extension is .txt./foo/bar/baz, the extension is an empty string./foo/bar/baz.tar.gz, the extension is .gz.The full filepath represented by this Path instance.
The root directory of the filepath.
⚠️ 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
/foo/bar/baz, the root directory is /.C:\foo\bar\baz, the root directory is C: (expressed as C:/ in this library).The portion of the basename without the extension.
/foo/bar/baz.txt, the stem is baz./foo/bar/baz, the stem is baz.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.⚠️
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);
>>> []
Asynchronously tests a user's permissions for the underling filepath.
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.
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.
Optional mode: undefinedSynchronously tests a user's permissions for the underling filepath.
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.
Optional mode: numberthe 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.
Optional mode: undefinedAlias 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. ⚠️
A new Path instance with the strings appended.
Rest ...segments: string[]Strings which should be appended to the Path instance in order to create a new one.
Asynchronously changes the permissions of the underlying filepath.
Returns the Path instance that called this method.
A string (i.e. fs.constants) or octal number (ex. 0o511) representation of the new filepath permissions.
Synchronously changes the permissions of the underlying filepath.
Returns the Path instance that called this method.
A string (i.e. fs.constants) or octal number (ex. 0o511) representation of the new filepath permissions.
Asynchronously determines whether a directory contains a given child filepath or basename.
The located child as a Path instance or false if no child path could be found.
// 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
The child filepath to look for within the underlying filepath. The following are accepted:
Synchronously determines whether a directory contains a given child filepath or basename.
The located child as a Path instance or false if no child path could be found.
// 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
The child filepath to look for within the underlying filepath. The following are accepted:
Asynchronously copies the underlying filepath to the indicated destination.
The filepath destination to where the underlying path should be copied.
Optional options: CopyOptionsCopyOptions By default:
overwrite is set to trueerrorOnExist is set to falsedereference is set to `falsepreserveTimestamps is set to falseinterRelativeSource is set to undefined (relative paths will be resolved relative to the current working directory)Synchronously copies the underlying filepath to the indicated destination.
The filepath destination to where the underlying path should be copied.
Optional options: CopyOptionsSyncCopyOptions By default:
overwrite is set to trueerrorOnExist is set to falsedereference is set to `falsepreserveTimestamps is set to falseinterRelativeSource is set to undefined (relative paths will be resolved relative to the current working directory)Retrieves filepaths located exactly N levels away from the underlying filepath. Utilizes globbing under the hood, thereby requiring glob options.
Depends on the asIterator parameter:
AsyncIterator of Path instancesArray of Path instancesThe depth to retrieve filepaths from. Interpretation is as follows:
Optional asIterator: trueWhether the result should be an AsyncIterator of Path instances instead of an Array of them.
Defaults to false.
Optional options: GlobOptionsOptions 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: falseonlyDirectories: falsedot: false (filepaths with basenames starting with a dot are ignored)Optional asIterator: falseOptional options: GlobOptionsAsynchronously globs for filepaths stemming from the Path instance.
An Array of globbed Path instances.
A string or collection of strings representing glob patterns to search.
Optional options: GlobOptionsfast-glob options. By default:
objectMode is set to false and enforcedstats is set to false and enforcedonlyDirectories is set to falseonlyFiles is set to falsedot is set to falseAsynchronously glob for filepaths stemming from the Path instance while yielding them instead of returning an immediate array.
Path instances.
A string or collection of strings representing glob patterns to search.
Optional options: GlobOptionsfast-glob options. By default:
objectMode is set to false and enforcedstats is set to false and enforcedonlyDirectories is set to falseonlyFiles is set to falsedot is set to falseSynchronously globs for filepaths stemming from the Path instance.
An Array of globbed Path instances.
A string or collection of strings representing glob patterns to search.
Optional options: GlobOptionsfast-glob options. By default:
objectMode is set to false and enforcedstats is set to false and enforcedonlyDirectories is set to falseonlyFiles is set to falsedot is set to falseAppends 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. ⚠️
A new Path instance with the strings appended.
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"
Rest ...segments: string[]Strings which should be appended to the Path instance in order to create a new one.
Asynchronously creates a new directory, including intermediate parental components.
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.
An octal number (ex. 0o511) representing of the new filepath permissions to impart. Defaults to 0o777.
Whether to rethrow any generated error. Defaults to false.
Synchronously creates a new directory, including intermediate parental components.
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.
An octal number (ex. 0o511) representing of the new filepath permissions to impart. Defaults to 0o777.
Whether to rethrow any generated error. Defaults to false.
Asynchronously creates a new file, including intermediate parental components.
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.
Whether to rethrow any generated error. Defaults to false.
Synchronously creates a new file, including intermediate parental components.
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.
Whether to rethrow any generated error. Defaults to false.
Asynchronously creates a symlink. Either:
The filepath outlined in target as a Path instance.
The corresponding target filepath that a symlink should be made to OR that is a symlink linking to the underlying filepath.
Optional options: SymlinkOptionsSymlinkOptions 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.Synchronously creates a symlink. Either:
The filepath outlined in target as a Path instance.
The corresponding target filepath that a symlink should be made to OR that is a symlink linking to the underlying filepath.
Optional options: SymlinkOptionsSymlinkOptions 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.Asynchronously moves the underlying filepath to the indicated destination.
Returns the destination filepath as a Path instance.
The filepath destination to where the underlying path should be moved.
Optional options: MoveOptionsMoveOptions By default:
overwrite is set to trueinterRelativeSource is set to undefined (relative paths will be resolved relative to the current working directory)Synchronously moves the underlying filepath to the indicated destination.
Returns the destination filepath as a Path instance.
The filepath destination to where the underlying path should be moved.
Optional options: MoveOptionsMoveOptions By default:
overwrite is set to trueinterRelativeSource is set to undefined (relative paths will be resolved relative to the current working directory)Asynchronously opens a file and returns its file descriptor.
The numeric file descriptor.
Synchronously opens a file and returns its file descriptor.
The numeric file descriptor.
Retrieves the parent directory or an earlier ancestor filepath.
The parent or higher ancestor (i.e grandparent) directory of this filepath as a Path instance.
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"
Optional numIncrements: numberThe number of directory levels to ascend.
Defaults to undefined, meaning that the immediate parent directory is returned.
Asynchronously reads a portion of the data from the underlying file.
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.
The Buffer that the data will be written to.
The position in buffer to write the data to.
The number of bytes to read.
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.
Whether to close the file after the operation completes. Defaults to true.
Optional openOptions: OpenFileOptionsAsynchronously parses data coming from a file.
The contents of the file either as a decoded string or as a Buffer if no encoding was provided.
Optional flag?: stringSynchronously parses data coming from a file.
The contents of the file either as a decoded string or as a Buffer if no encoding was provided.
Optional flag?: stringAsynchronously reads in the underlying filepath JSON file and parses it into a JSON object.
A JSON object.
Optional options: string | ReadOptionsAsynchronously retrieves the filepath that the underlying symlink is pointing to.
A Path instance of the target.
// 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"
Synchronously retrieves the filepath that the underlying symlink is pointing to.
A Path instance of the target.
// 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"
Synchronously reads a portion of the data from the underlying file.
The number of bytes read.
The Buffer that the data will be written to.
The position in buffer to write the data to.
The number of bytes to read.
Specifies where to begin reading from in the file.
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: OpenFileOptionsDepicts the relative path from the Path instance to another filepath.
A string representation of the relative path.
const fp = new Path("/home/jsmith/Documents")
console.log(fp.relative("/home"))
>>> "../.."
The filepath that this instance should be compared against.
Whether to present the final string in accordance with the operating
system's filepath delimiter. Default is false.
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. ⚠️
The resolved Path instance.
const fp = new Path("/home/jsmith/Documents")
console.log(fp.resolve("../Downloads").path)
>>> "/home/jsmith/Downloads"
Rest ...segments: string[]An Array of strings respresenting path segments to append and resolve to the underlying path.
Depicts an Object version of the Path instance.
An Object representation of the underlying filepath; PathJSON.
Whether to respect the system-specific filepath delimiter. Defaults to false.
Depicts a string version of the Path instance.
A string representation of the underlying filepath.
Whether to respect the system-specific filepath delimiter. Defaults to false.
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.
A representation of the filepath tree structure.
Optional asString: trueWhether to convert the "filepath" property automatically to a string representation of the path instead.
Optional useSystemPathDelimiter: booleanOptional asString: falseOptional useSystemPathDelimiter: booleanSynchronously 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.
A representation of the filepath tree structure.
Optional asString: trueWhether to convert the "filepath" property automatically to a string representation of the path instead.
Optional useSystemPathDelimiter: booleanOptional asString: falseOptional useSystemPathDelimiter: booleanAsynchronously 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.
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.
Wrapper around implementing a Chokidar watcher on the underlying filepath.
Either a PathWatcher instance (default) or a Promise that resolves to a PathWatcher instance if waitUntilReady is true.
Optional options: WatchOptionsChokidar options controlling the behavior of the filepath watcher.
Optional waitUntilReady: falseWhether to defer the return of the watcher until its "ready" event has been emitted. Defaults to undefined (will not wait for the ready event).
Optional options: WatchOptionsOptional waitUntilReady: trueCreates a new Path instance with a replaced basename.
A new Path instance featuring the replacement basename.
const fp = new Path("/home/jsmith/Documents/foo.txt")
console.log(fp.withBasename("bar.json").path)
>>> "/home/jsmith/Documents/bar.json"
The new basename to replace the existing one.
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(). ⚠️
A new Path instance featuring the replacement last extension.
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"
The new extension to replace the existing one.
Creates a new Path instance with a replaced stem.
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"
The new stem to replace the existing one.
Creates a new Path instance with a replaced set of suffix extensions.
A new Path instance featuring the replaced suffix(es).
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"
The new suffix to replace the existing one. Behavior patterns are as follows:
Array of strings, it will concatenate each with a "." character before appending to the existing stem.Asynchronously writes buffer-like data into the underlying file.
the Buffer which should be written into the underlying file.
Optional offset: numberThe position in the buffer from which to begin writing
Optional length: numberThe number of bytes to write.
Optional position: null | numberSpecifies where to begin writing into the file.
Whether to close the file after the operation completes. Defaults to true.
Optional openOptions: OpenFileOptionsAsynchronously writes data to the underlying filepath.
Returns the Path instance that called this method
The data to write to the file.
Optional options: WriteFileOptionsSynchronously writes data to the underlying filepath.
Returns the Path instance that called this method
The data to write to the file.
Optional options: WriteFileOptionsAsynchronously write a JSON-compatible object to a .json file.
Returns the Path instance which called this method.
A JSON-compatible object to write into the file.
Optional options: WriteOptionsSynchronously write a JSON-compatible object to a .json file.
Returns the Path instance which called this method.
A JSON-compatible object to write into the file.
Optional options: WriteOptionsSynchronously writes buffer-like data into the underlying file.
the Buffer which should be written into the underlying file.
Optional offset: numberThe position in the buffer from which to begin writing
Optional length: numberThe number of bytes to write.
Optional position: null | numberSpecifies where to begin writing into the file.
Whether to close the file after the operation completes. Defaults to true.
Optional openOptions: OpenFileOptionsStatic cwdStatic getPATHAsStatic homeStatic parseParses the mode of a filepath into a more understandable octal-like representation (i.e. 777 for full-permissions)
A 3-digit representation of the permissions indicated by the provided mode.
console.log(Path.parseModeIntoOctal(16877))
>>> 755
The mode of a filepath, as received from fs.Stats or the fs.Stats object itself
Static pwdStatic toJoins filepaths to create a single string representation, delimited by the system-specific environment delimiter.
Filepaths concatenated by the system-specific environment delimiter.
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.
Generated using TypeDoc
A wrapper class representing a filepath on which operations can be performed.
Example
Here are a few examples of how the Path class instantiates: