Creates a new FsPath
If given a relative path, it is resolved against the current working directory. The path is always normalized.
Creating an FsPath instance does not imply that the path exists on the filesystem; use exists, isFile, isDirectory or stat to check for existence, and use write, touch, makeDirectory, or makeTempDirectory to create files or directories.
Returns the extension of the filename including the leading dot, as a string. If the filename has no extension, returns an empty string.
Note that if the filename starts with a dot (e.g. .gitignore
),
that dot is considered part of the stem. So .gitignore
has
extension ''
and .gitignore.bak
has extension .bak
Returns the stem of the filename, i.e. the part before the extension. If the filename has no extension, returns the entire filename
Note that if the filename starts with a dot (e.g. .gitignore
),
that dot is considered part of the stem. So .gitignore
and
.gitignore.bak
both have stem .gitignore
Copies this file to a new location.
The target path to copy to.
Optional
opts: { intoDir?: boolean; makeParents?: boolean }Optional
intoDir?: booleanIf true, treat to
as a directory and copy the file into it. (Default: false)
Optional
makeParents?: booleanIf true, create parent directories of the target path as needed. (Default: false)
A Promise resolving to a new FsPath for the path of the copy (either to
or to.join(this.filename)
based on opts.intoDir
)
const p1 = new FsPath('/path/to/file.txt')
const p2 = new FsPath('/new/path/to/file.txt')
await p1.copyTo(p2, { makeParents: true }) // Copies the file, creating parent directories as needed
const dir = new FsPath('/new/path/')
const p3 = await p1.copyTo(dir, { intoDir: true, makeParents: true }) // Copies the file into the directory
console.log(p3.toString()) // /new/path/file.txt
Test whether this path is a descendant of the given ancestor path.
An AbsolutePath
or string to check against.
Optional
opts: { includeSelf?: boolean }Optional
includeSelf?: booleanIf true, return true when the paths are identical.
True if this path descends from the ancestor, otherwise false.
Create an FsPath instance marked as as disposable, meaning the file or directory will be automatically deleted when no longer needed.
Disposable paths will be disposed (i.e. the file or directory will be deleted) in one of three circumstances, whichever comes first:
Via the using
declaration
-- the path is disposed as soon as the declared variable goes out of scope.
This is the most immediate and reliable.
Disposal when the FsPath object is garbage collected. As always, there's no knowing when or if this will happen.
Disposal on process exit.
⚠️ Disposal is best-effort; it may fail due to permissions or be skipped if the process exits abnormally. Failures during disposal are silently ignored.
A new instance of this path, marked as disposable.
{
using p = new FsPath('/path/to/tempfile.txt').disposable()
await p.write('data') // Creates the file
...
} // The file is automatically removed when p goes out of scope
const p2 = new FsPath('/path/to/tempfile2.txt').disposable()
await p2.write('data')
// The file will be removed eventually, on gc or process exit
Returns true if this path equals the other path or string
Finds files and directories matching a glob pattern within this directory.
Uses fast-glob under the hood.
The glob pattern to match
Optional
opts: FsReadDirectoryOptionsOptions for reading directories, used by FsPath.readDirectory and FsPath.glob
Optional
allowMissing?: booleanIf true, return an empty array if the directory does not exist, rather than throwing an error. (Default: false)
Optional
includeDotfiles?: booleanIf true, include dotfiles in the result. (Default: true)
Optional
onlyDirs?: booleanIf true, only include directories in the result. (Default: false)
Optional
onlyFiles?: booleanIf true, only include files in the result. (Default: false)
An array of FsPath objects representing the matching entries.
Join additional path segments to this path.
Accepts strings or path objects; null
and undefined
are ignored.
The resulting path is normalized.
A new path instance with the segments appended
const a1 = new AbsolutePath('/project/demo')
const a2 = a1.join('demo1/src', 'index.js') // '/project/demo/demo1/src/index.js'
a2 instanceof AbsolutePath // true
const r1 = new RelativePath('demo')
const r2 = r1.join('demo1/src', 'index.js') // 'demo/demo1/src/index.js'
r2 instanceof RelativePath // true
Create a directory at this path.
Optional
opts: { makeParents?: boolean }Optional
makeParents?: booleanIf true, create parent directories as needed.
A Promise resolving to this instance, for chaining.
Move (rename) this file or directory to a new location.
The target path to move to.
Optional
opts: { intoDir?: boolean; makeParents?: boolean }Optional
intoDir?: booleanIf true, treat to
as a directory and move the file into it. (Default: false)
Optional
makeParents?: booleanIf true, create parent directories of the target path as needed. (Default: false)
A Promise resolving to a new FsPath for the final path (either to
or to.join(this.filename)
based on opts.intoDir
)
const p1 = new FsPath('/path/to/file.txt')
const p2 = new FsPath('/new/path/to/file.txt')
await p1.moveTo(p2, { makeParents: true }) // Renames (moves) the file, creating parent directories as needed
const dir = new FsPath('/new/path/')
const p3 = await p2.moveTo(dir, { intoDir: true, makeParents: true }) // Moves the file into the directory
console.log(p3.toString()) // /new/path/file.txt
Protected
newProtected factory to construct a new instance of the current class, with the given path.
Used by all mutation-like methods to return a new instance of the same class, allowing derived classes that inherit those methods to return new instances of themselves without needing to override them.
The default implementation assumes the derived class's constructor takes a single string argument (the path). Derived classes with different constructor siguatures should override newSelf.
Reads the contents of the directory.
Optional
opts: FsReadDirectoryOptionsOptions for reading directories, used by FsPath.readDirectory and FsPath.glob
Optional
allowMissing?: booleanIf true, return an empty array if the directory does not exist, rather than throwing an error. (Default: false)
Optional
includeDotfiles?: booleanIf true, include dotfiles in the result. (Default: true)
Optional
onlyDirs?: booleanIf true, only include directories in the result. (Default: false)
Optional
onlyFiles?: booleanIf true, only include files in the result. (Default: false)
An array of FsPath objects representing the entries in the directory.
Creates a readable stream for the file.
Optional
opts: { end?: number; start?: number }Optional
end?: numberThe ending byte position (inclusive).
Optional
start?: numberThe starting byte position (inclusive).
A readable stream for the file.
Compute the relative path from the given base path to this path.
The base absolute path.
A RelativePath that goes from base
to this
.
Removes the file or directory.
Optional
opts: { throwIfMissing?: boolean }Optional
throwIfMissing?: booleanIf true, throw an error if the path does not exist. (Default: false)
A Promise resolving to this instance, for chaining. (The path object remains valid even though the file or directory has been removed.)
Replace the filename extension, keeping the stem the same. The passed can include or omit the leading dot; if omitted, it will be added.
New extension, e.g. json
or .json
A new path with the extension replaced.
Replace the filename (last segment).
A new path with the filename replaced.
Replace the parent directory while keeping the current filename.
Parent directory as string or another PathBase
.
A new path rooted at newParent
with the same filename.
Replace the filename stem, keeping the extension the same
New stem to use (extension is preserved).
A new path with the stem replaced.
Resolve additional path segments against this absolute path.
Accepts strings, Filename, RelativePath, or AbsolutePath objects. Null and undefined segments are ignored.
Similar to join, except that if any segment is an AbsolutePath or string starting with a path separator, the current path is discarded and resolution starts from that segment.
A new AbsolutePath with the resolved path.
Cancels disposal for this instance.
If this instance was created via disposable(), so that file or
directory would be automatically removed, calling retain()
prevents
that removal.
A new instance of this path, unmarked as disposable.
⚠️ The old instance remains valid and can still be used normally. Technically the old instance continues to to be marked as disposable, but its disposal will now be a no-op.
{
using p = new FsPath('/path/to/tempfile.txt').disposable()
await p.write('data') // Creates the file
...
p.retain() // The file will *not* be removed when p goes out of scope
}
const p2 = new FsPath('/path/to/tempfile2.txt').disposable()
await p2.write('data')
p2.retain() // the file will *not* be automatically removed
Sets the permission mode of the path.
The permission specification. Can be the numeric mode, or an object specifying user/group/others permissions.
Optional
opts: { operation: "clear" | "overlay" | "assign" }The operation to perform: assign the permissions exactly (default), overlay the permissions on top of the existing ones, or clear the specified permissions from the existing ones.
A Promise resolving to this instance, for chaining.
const p = new FsPath('/path/to/file')
// Set to rw-r--r--
await p.setPermissions({ mode: 0o644 })
// Add write permission for all => rw-rw-rw-
await p.setPermissions({ all: { read: true, write: true } }, { operation: 'overlay' })
// Remove write permission for others => rw-rw-r--
await p.setPermissions({ others: { write: true } }, { operation: 'clear' })
Returns the path as string.
Updates the file's access and modification times, or create an empty file if it does not exist.
Optional
opts: { makeParents?: boolean }Optional
makeParents?: booleanIf true, create parent directories as needed. (Default: false)
A Promise resolving to this instance, for chaining.
Writes content to the file, replacing or appending to the existing content.
The content to write (string or Uint8Array).
Optional
opts: { append?: boolean; encoding?: BufferEncoding; makeParents?: boolean }Optional
append?: booleanIf true, append to the file instead of replacing it. (Default: false)
Optional
encoding?: BufferEncodingThe file encoding. (Default: 'utf8' if content is string)
Optional
makeParents?: booleanIf true, create parent directories as needed. (Default: false)
A Promise resolving to this instance, for chaining.
Static
cwdStatic
isChecks whether a string is an absolute path. (I.e., if it would be acceptable to the AbsolutePath constructor.)
The string to check.
True if the string is an absolute path, otherwise false.
Static
makeCreates a new temporary directory under the system temporary directory.
The directory is marked as disposable().
Optional
opts: { prefix?: string }
Represents an absolute filesystem path (i.e. a path starting at the root with a leading separator), and provides methods for path resolution, manipulation and queries as well as (async) filesystem operations.
FsPath instances are normalized and immutable.
FsPath extends AbsolutePath of
@thingts/path
, but with added methods for filesystem access.Having an FsPath does not imply that a file or directory exists at that path in the filesystem; use exists, isFile, isDirectory or stat to check for existence, and use write, touch, makeDirectory, or makeTempDirectory to create files or directories.
Methods that create or modify files or directories return a
Promise<this>
, allowing for chaining.⚠️ In the documentation below that is inherited from AbsolutePath, examples that refer to
AbsolutePath
apply equally toFsPath
-- in particular, the path manipulation methods like join returnFsPath
instances, notAbsolutePath
instances.Example