File Paths
The path
module provides utilities for working with file and directory paths.
When working with file systems and handling file paths dynamically, correctly manipulating and resolving file paths will ensure your program works correctly on any operating system.
Joining paths
The path.join
function correctly joins path segments.
Note that path.join
should not be used with URLs that contain a protocol like https://
.
Parsing a path
The path.parse
function produces an object with useful information about the path.
Formatting a path
An object like the one produced by path.parse
can be converted back into a correctly formatted path with path.format
.
Note that if you are using this function to change some particular information about the path - for example, the file extension -
you need to update both ext
and base
. Consider the example below, which computes the path to a compiled .js
file
corresponding to an original Typescript .ts
file.
Joining paths
Joins all given path segments into a single normalized path.
Zero-length path segments are ignored, which allows you to safely use a string to serve as a path modifier. You cannot use
null
or undefined
as a path segment for path.join
.
Base name
The path separator can vary based on operating system, namely for Windows and POSIX systems. To ensure consistent results,
use path.win32
when working with Windows file paths, and path.posix
when working with POSIX file paths.
Directory name
Returns the parent directory for the given path.
Platform constants
There are two platform-specific constants - sep
and delimiter
. The platform-specific path segment separator in sep
is \
on Windows and /
on POSIX, and the delimiter
is ;
on Windows and :
on POSIX.
These values are commonly used in split
operations that should be platform-independent.