Creates a new FsPath instance
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
Checks the accessibility of the path with the specified mode(s).
Note that a successful access check does not guarantee that a subsequent operation will succeed, since the filesystem state may change in between.
The access mode(s) to check. Can be a FsFileMode string, an array of FsFileMode strings, or an
FsPermissionFlags object specifying read/write/execute
booleans. An empty spec ([] or {}) checks for
existence.
Optionalopts: { throw?: boolean }
Optionalthrow?: booleanIf true, rethrows the underlying filesystem error if the path is not accessible with the specified mode(s). (Default: false)
A Promise resolving to true if the path is accessible with
the specified mode(s), or false if it is not (and opts.throw is
false).
Copies this file or directory to a new location.
By default:
recursive: true; otherwise an error is thrown.overwrite: false is specified.The target path to copy to.
Optionalopts: {OptionalintoDir?: booleanIf true, treat to as a directory and copy this path into it
(i.e. to.join(this.filename)). (Default: false)
OptionalmakeParents?: booleanIf true, create parent directories of the target path as needed. (Default: false)
Optionaloverwrite?: booleanIf false, do not overwrite existing files; instead throw an error if a destination path already exists. (Default: true)
Optionalrecursive?: booleanIf true, allow copying directories recursively. Required when the source is a directory. (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 src = new FsPath('/path/to/file.txt')
const dest = new FsPath('/new/path/to/file.txt')
await src.copyTo(dest) // overwrites dest if it exists
const dir = new FsPath('/new/path/')
await src.copyTo(dir, { intoDir: true }) // copies to /new/path/file.txt
const srcDir = new FsPath('/path/to/dir')
await srcDir.copyTo('/backup/dir', { recursive: true }) // copies entire directory tree
await src.copyTo(dest, { overwrite: false }) // throws if dest exists
Test whether this path is a descendant of the given ancestor path.
An AbsolutePath or string to check against.
Optionalopts: { includeSelf?: boolean }
OptionalincludeSelf?: booleanIf true, return true when the paths are identical.
True if this path descends from the ancestor, otherwise false.
Marks the file or directory at this path as disposable, meaning it is registered for automatic deletion.
A disposable path is deleted either:
when leaving the scope of a using
declaration (via Symbol.dispose)
on normal process exit.
Disposability is associated with the normalized path string, not
with this particular FsPath instance. Any other FsPath
instance referring to the same path shares the same disposability
state, and can call retain() to cancel it.
⚠️ Disposal is best-effort; it may fail due to permissions or be skipped if the process exits abnormally. Failures during disposal are silently ignored.
This instance, for chaining
Returns true if this path equals the other path or path string.
Finds files and directories matching a glob pattern within this directory.
Uses tinyglobby under the hood.
The glob pattern to match
Optionalopts: FsReadDirectoryOptions
Options for reading directories, used by readDirectory() and
glob().
OptionalallowMissing?: booleanIf true, return an empty array if the directory does not exist, rather than throwing an error. (Default: false)
OptionalincludeDotfiles?: booleanIf true, include dotfiles in the result. (Default: true)
OptionalonlyDirs?: booleanIf true, only include directories in the result. (Default: false)
OptionalonlyFiles?: 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 relative path objects and Filename segment arguments for type safety, but you can also directly pass strings for convenience. All args are stringified and interpreted as segments to be joined, regardless of whether they start with a path separator.
Any null, undefined, or empty segments are ignored.
A new instance with the segments appended and resulting path normalized.
Create a directory at this path
By default, if the directory already exists, this succeeds as a no-op (that is, the operation is idempotent).
Optionalopts: { makeParents?: boolean; throwIfExists?: boolean }
OptionalmakeParents?: booleanIf true, create parent directories as needed.
OptionalthrowIfExists?: booleanIf true, throw an error if the final directory already exists. (Default: false)
A Promise resolving to this instance, for chaining.
Move (rename) this file or directory to a new location.
The target path to move to.
Optionalopts: { intoDir?: boolean; makeParents?: boolean; overwrite?: boolean }
OptionalintoDir?: booleanIf true, treat to as a directory and move the file into it. (Default: false)
OptionalmakeParents?: booleanIf true, create parent directories of the target path as needed. (Default: false)
Optionaloverwrite?: booleanIf false, do not overwrite an existing file; instead throw an error if the final destination path already exists. (Default: true)
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
Read the contents of the file as a string.
Optionalopts: { encoding?: BufferEncoding }
Optionalencoding?: BufferEncodingThe file encoding. (Default: 'utf8')
The file contents as a string.
Reads a range of bytes from the file.
This method is useful for inspecting file headers, magic bytes, or other binary metadata without reading the entire file into memory.
If the requested range extends beyond the end of the file, the returned buffer will contain only the bytes that were successfully read.
Optionaloffset?: numberByte offset at which to begin reading. Defaults to 0.
Maximum number of bytes to read.
Reads the contents of the directory.
Optionalopts: FsReadDirectoryOptions
Options for reading directories, used by readDirectory() and
glob().
OptionalallowMissing?: booleanIf true, return an empty array if the directory does not exist, rather than throwing an error. (Default: false)
OptionalincludeDotfiles?: booleanIf true, include dotfiles in the result. (Default: true)
OptionalonlyDirs?: booleanIf true, only include directories in the result. (Default: false)
OptionalonlyFiles?: 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.
Optionalopts: { end?: number; start?: number }
Optionalend?: numberThe ending byte position (inclusive).
Optionalstart?: numberThe starting byte position (inclusive).
A readable stream for the file.
Compute the relative path from the given base path to this path.
If the base path is not an ancestor of this path, the returned
relative path will start with .. segments to navigate up through a
common ancestor. If the base path is the same as this path, the
returned relative path will be ..
The base absolute path.
A RelativePath that goes from base to this.
const p1 = new AbsolutePath('/project/demo')
const p2 = new AbsolutePath('/project/demo/src/index.ts')
const rel = p2.relativeTo(p1) // 'src/index.ts' (RelativePath)
p1.join(rel).equals(p2) // true
const p3 = new AbsolutePath('/project/demo/bin/doit')
const rel2 = p3.relativeTo(p2) // '../../bin/doit' (RelativePath)
p2.join(rel2).equals(p3) // true
const rel3 = p1.relativeTo(p1) // '.' (RelativePath)
Removes the file or directory.
Optionalopts: { throwIfMissing?: boolean }
OptionalthrowIfMissing?: 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 (last segment).
A new instance with the filename replaced.
Replace the entire directory path through the parent, while keeping the current filename.
Parent directory as string or another path
A new path rooted at newParent with the same filename.
Cancels disposal for this path.
Since disposability is associated with the path string rather than a
particular FsPath instance, retain() can be called on any
instance referring to the same path as one previously marked with
disposable() -- it does not need to be the
same instance.
This instance, for chaining
{
using p = new FsPath('/path/to/tempfile.txt').disposable()
await p.touch() // 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.touch()
p2.retain() // the file will *not* be removed on process exit
// Retaining via an equivalent (but distinct) instance also works:
const p3 = new FsPath('/path/to/tempfile3.txt').disposable()
await p3.touch()
new FsPath(p3).retain() // the file will *not* be removed on process exit
Sets the permission mode of the path.
The permission specification. Can be the numeric mode, or an object specifying user/group/others permissions; each category can be specified with a FsFileMode string, an array of FsFileMode strings, or an FsPermissionFlags object specifying read/write/execute booleans.
Optionalopts: { operation?: "clear" | "overlay" | "assign" }
Optionaloperation?: "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', 'write'] }, { operation: 'overlay' })
// Remove write permission for others => rw-rw-r--
await p.setPermissions({ others: { write: true } }, { operation: 'clear' })
Returns the string representation of this path.
Updates the file's access and modification times, or create an empty file if it does not exist.
Optionalopts: { makeParents?: boolean }
OptionalmakeParents?: 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).
Optionalopts: { append?: boolean; encoding?: BufferEncoding; makeParents?: boolean }
Optionalappend?: booleanIf true, append to the file instead of replacing it. (Default: false)
Optionalencoding?: BufferEncodingThe file encoding. (Default: 'utf8' if content is string)
OptionalmakeParents?: booleanIf true, create parent directories as needed. (Default: false)
A Promise resolving to this instance, for chaining.
StaticcwdStaticmakeCreates a new temporary directory
By default, the directory is created under the system temporary
directory (see os.tmpdir)
The resulting directory name will begin with the given prefix
(default: 'temp-') followed by a unique suffix, as per
fs.mkdtemp.
The returned FsPath is marked as disposable for automatic deletion.
Optionalopts: { makeParents?: boolean; parent?: AbsolutePath; prefix?: string }
OptionalmakeParents?: booleanIf true, create the parent directory if it does not exist. (Default: false)
Optionalparent?: AbsolutePathThe parent directory in which to create the temporary directory. Defaults to the system temporary directory.
Optionalprefix?: stringPrefix for the generated directory name. (Default: 'temp-'`)
A Promise resolving to a new FsPath representing the temporary directory, marked as disposable.
// Default: create under system temp directory
const dir = await FsPath.makeTempDirectory()
// With custom prefix
const dir2 = await FsPath.makeTempDirectory({ prefix: 'build-' })
// Under a custom parent directory
const dir3 = await FsPath.makeTempDirectory({
parent: '/projects/demo/.tmp',
prefix: 'build-',
makeParents: true
})
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 instance does not imply that a file or directory exists at that path in the filesystem; use
exists(),isFile(),isDirectory()orstat()to check for existence, and usewrite(),touch(),makeDirectory(), ormakeTempDirectory()to create files or directories.Methods that create or modify files or directories return a
Promise<this>, allowing for chaining.FsPath also supports creating temporary files or directories; see
disposable()⚠️ In the documentation below that is inherited from AbsolutePath, examples that refer to
AbsolutePathapply equally toFsPath-- in particular, the path manipulation methods likejoin()returnFsPathinstances, notAbsolutePathinstances.Example