Path#
Source Code:lib/path.js
Thenode:path
module provides utilities for working with file and directorypaths. It can be accessed using:
const path =require('node:path');
import pathfrom'node:path';
Windows vs. POSIX#
The default operation of thenode:path
module varies based on the operatingsystem on which a Node.js application is running. Specifically, when running ona Windows operating system, thenode:path
module will assume thatWindows-style paths are being used.
So usingpath.basename()
might yield different results on POSIX and Windows:
On POSIX:
path.basename('C:\\temp\\myfile.html');// Returns: 'C:\\temp\\myfile.html'
On Windows:
path.basename('C:\\temp\\myfile.html');// Returns: 'myfile.html'
To achieve consistent results when working with Windows file paths on anyoperating system, usepath.win32
:
On POSIX and Windows:
path.win32.basename('C:\\temp\\myfile.html');// Returns: 'myfile.html'
To achieve consistent results when working with POSIX file paths on anyoperating system, usepath.posix
:
On POSIX and Windows:
path.posix.basename('/tmp/myfile.html');// Returns: 'myfile.html'
On Windows Node.js follows the concept of per-drive working directory.This behavior can be observed when using a drive path without a backslash. Forexample,path.resolve('C:\\')
can potentially return a different result thanpath.resolve('C:')
. For more information, seethis MSDN page.
path.basename(path[, suffix])
#
History
Version | Changes |
---|---|
v6.0.0 | Passing a non-string as the |
v0.1.25 | Added in: v0.1.25 |
Thepath.basename()
method returns the last portion of apath
, similar tothe Unixbasename
command. Trailingdirectory separators areignored.
path.basename('/foo/bar/baz/asdf/quux.html');// Returns: 'quux.html'path.basename('/foo/bar/baz/asdf/quux.html','.html');// Returns: 'quux'
Although Windows usually treats file names, including file extensions, in acase-insensitive manner, this function does not. For example,C:\\foo.html
andC:\\foo.HTML
refer to the same file, butbasename
treats the extension as acase-sensitive string:
path.win32.basename('C:\\foo.html','.html');// Returns: 'foo'path.win32.basename('C:\\foo.HTML','.html');// Returns: 'foo.HTML'
ATypeError
is thrown ifpath
is not a string or ifsuffix
is givenand is not a string.
path.delimiter
#
Provides the platform-specific path delimiter:
;
for Windows:
for POSIX
For example, on POSIX:
console.log(process.env.PATH);// Prints: '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'process.env.PATH.split(path.delimiter);// Returns: ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']
On Windows:
console.log(process.env.PATH);// Prints: 'C:\Windows\system32;C:\Windows;C:\Program Files\node\'process.env.PATH.split(path.delimiter);// Returns ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\']
path.dirname(path)
#
History
Version | Changes |
---|---|
v6.0.0 | Passing a non-string as the |
v0.1.16 | Added in: v0.1.16 |
Thepath.dirname()
method returns the directory name of apath
, similar tothe Unixdirname
command. Trailing directory separators are ignored, seepath.sep
.
path.dirname('/foo/bar/baz/asdf/quux');// Returns: '/foo/bar/baz/asdf'
ATypeError
is thrown ifpath
is not a string.
path.extname(path)
#
History
Version | Changes |
---|---|
v6.0.0 | Passing a non-string as the |
v0.1.25 | Added in: v0.1.25 |
Thepath.extname()
method returns the extension of thepath
, from the lastoccurrence of the.
(period) character to end of string in the last portion ofthepath
. If there is no.
in the last portion of thepath
, or ifthere are no.
characters other than the first character ofthe basename ofpath
(seepath.basename()
) , an empty string is returned.
path.extname('index.html');// Returns: '.html'path.extname('index.coffee.md');// Returns: '.md'path.extname('index.');// Returns: '.'path.extname('index');// Returns: ''path.extname('.index');// Returns: ''path.extname('.index.md');// Returns: '.md'
ATypeError
is thrown ifpath
is not a string.
path.format(pathObject)
#
History
Version | Changes |
---|---|
v19.0.0 | The dot will be added if it is not specified in |
v0.11.15 | Added in: v0.11.15 |
Thepath.format()
method returns a path string from an object. This is theopposite ofpath.parse()
.
When providing properties to thepathObject
remember that there arecombinations where one property has priority over another:
pathObject.root
is ignored ifpathObject.dir
is providedpathObject.ext
andpathObject.name
are ignored ifpathObject.base
exists
For example, on POSIX:
// If `dir`, `root` and `base` are provided,// `${dir}${path.sep}${base}`// will be returned. `root` is ignored.path.format({root:'/ignored',dir:'/home/user/dir',base:'file.txt',});// Returns: '/home/user/dir/file.txt'// `root` will be used if `dir` is not specified.// If only `root` is provided or `dir` is equal to `root` then the// platform separator will not be included. `ext` will be ignored.path.format({root:'/',base:'file.txt',ext:'ignored',});// Returns: '/file.txt'// `name` + `ext` will be used if `base` is not specified.path.format({root:'/',name:'file',ext:'.txt',});// Returns: '/file.txt'// The dot will be added if it is not specified in `ext`.path.format({root:'/',name:'file',ext:'txt',});// Returns: '/file.txt'
On Windows:
path.format({dir:'C:\\path\\dir',base:'file.txt',});// Returns: 'C:\\path\\dir\\file.txt'
path.matchesGlob(path, pattern)
#
path
<string> The path to glob-match against.pattern
<string> The glob to check the path against.- Returns:<boolean> Whether or not the
path
matched thepattern
.
Thepath.matchesGlob()
method determines ifpath
matches thepattern
.
For example:
path.matchesGlob('/foo/bar','/foo/*');// truepath.matchesGlob('/foo/bar*','foo/bird');// false
ATypeError
is thrown ifpath
orpattern
are not strings.
path.isAbsolute(path)
#
Thepath.isAbsolute()
method determines if the literalpath
is absolute.Therefore, it’s not safe for mitigating path traversals.
If the givenpath
is a zero-length string,false
will be returned.
For example, on POSIX:
path.isAbsolute('/foo/bar');// truepath.isAbsolute('/baz/..');// truepath.isAbsolute('/baz/../..');// truepath.isAbsolute('qux/');// falsepath.isAbsolute('.');// false
On Windows:
path.isAbsolute('//server');// truepath.isAbsolute('\\\\server');// truepath.isAbsolute('C:/foo/..');// truepath.isAbsolute('C:\\foo\\..');// truepath.isAbsolute('bar\\baz');// falsepath.isAbsolute('bar/baz');// falsepath.isAbsolute('.');// false
ATypeError
is thrown ifpath
is not a string.
path.join([...paths])
#
Thepath.join()
method joins all givenpath
segments together using theplatform-specific separator as a delimiter, then normalizes the resulting path.
Zero-lengthpath
segments are ignored. If the joined path string is azero-length string then'.'
will be returned, representing the currentworking directory.
path.join('/foo','bar','baz/asdf','quux','..');// Returns: '/foo/bar/baz/asdf'path.join('foo', {},'bar');// Throws 'TypeError: Path must be a string. Received {}'
ATypeError
is thrown if any of the path segments is not a string.
path.normalize(path)
#
Thepath.normalize()
method normalizes the givenpath
, resolving'..'
and'.'
segments.
When multiple, sequential path segment separation characters are found (e.g./
on POSIX and either\
or/
on Windows), they are replaced by a singleinstance of the platform-specific path segment separator (/
on POSIX and\
on Windows). Trailing separators are preserved.
If thepath
is a zero-length string,'.'
is returned, representing thecurrent working directory.
On POSIX, the types of normalization applied by this function do not strictlyadhere to the POSIX specification. For example, this function will replace twoleading forward slashes with a single slash as if it was a regular absolutepath, whereas a few POSIX systems assign special meaning to paths beginning withexactly two forward slashes. Similarly, other substitutions performed by thisfunction, such as removing..
segments, may change how the underlying systemresolves the path.
For example, on POSIX:
path.normalize('/foo/bar//baz/asdf/quux/..');// Returns: '/foo/bar/baz/asdf'
On Windows:
path.normalize('C:\\temp\\\\foo\\bar\\..\\');// Returns: 'C:\\temp\\foo\\'
Since Windows recognizes multiple path separators, both separators will bereplaced by instances of the Windows preferred separator (\
):
path.win32.normalize('C:////temp\\\\/\\/\\/foo/bar');// Returns: 'C:\\temp\\foo\\bar'
ATypeError
is thrown ifpath
is not a string.
path.parse(path)
#
Thepath.parse()
method returns an object whose properties representsignificant elements of thepath
. Trailing directory separators are ignored,seepath.sep
.
The returned object will have the following properties:
For example, on POSIX:
path.parse('/home/user/dir/file.txt');// Returns:// { root: '/',// dir: '/home/user/dir',// base: 'file.txt',// ext: '.txt',// name: 'file' }
┌─────────────────────┬────────────┐│ dir │ base │├──────┬ ├──────┬─────┤│ root │ │ name │ ext │" / home/user/dir / file .txt "└──────┴──────────────┴──────┴─────┘(All spaces in the "" line should be ignored. They are purely for formatting.)
On Windows:
path.parse('C:\\path\\dir\\file.txt');// Returns:// { root: 'C:\\',// dir: 'C:\\path\\dir',// base: 'file.txt',// ext: '.txt',// name: 'file' }
┌─────────────────────┬────────────┐│ dir │ base │├──────┬ ├──────┬─────┤│ root │ │ name │ ext │" C:\ path\dir \ file .txt "└──────┴──────────────┴──────┴─────┘(All spaces in the "" line should be ignored. They are purely for formatting.)
ATypeError
is thrown ifpath
is not a string.
path.posix
#
History
Version | Changes |
---|---|
v15.3.0 | Exposed as |
v0.11.15 | Added in: v0.11.15 |
Thepath.posix
property provides access to POSIX specific implementationsof thepath
methods.
The API is accessible viarequire('node:path').posix
orrequire('node:path/posix')
.
path.relative(from, to)
#
History
Version | Changes |
---|---|
v6.8.0 | On Windows, the leading slashes for UNC paths are now included in the return value. |
v0.5.0 | Added in: v0.5.0 |
Thepath.relative()
method returns the relative path fromfrom
toto
basedon the current working directory. Iffrom
andto
each resolve to the samepath (after callingpath.resolve()
on each), a zero-length string is returned.
If a zero-length string is passed asfrom
orto
, the current workingdirectory will be used instead of the zero-length strings.
For example, on POSIX:
path.relative('/data/orandea/test/aaa','/data/orandea/impl/bbb');// Returns: '../../impl/bbb'
On Windows:
path.relative('C:\\orandea\\test\\aaa','C:\\orandea\\impl\\bbb');// Returns: '..\\..\\impl\\bbb'
ATypeError
is thrown if eitherfrom
orto
is not a string.
path.resolve([...paths])
#
Thepath.resolve()
method resolves a sequence of paths or path segments intoan absolute path.
The given sequence of paths is processed from right to left, with eachsubsequentpath
prepended until an absolute path is constructed.For instance, given the sequence of path segments:/foo
,/bar
,baz
,callingpath.resolve('/foo', '/bar', 'baz')
would return/bar/baz
because'baz'
is not an absolute path but'/bar' + '/' + 'baz'
is.
If, after processing all givenpath
segments, an absolute path has not yetbeen generated, the current working directory is used.
The resulting path is normalized and trailing slashes are removed unless thepath is resolved to the root directory.
Zero-lengthpath
segments are ignored.
If nopath
segments are passed,path.resolve()
will return the absolute pathof the current working directory.
path.resolve('/foo/bar','./baz');// Returns: '/foo/bar/baz'path.resolve('/foo/bar','/tmp/file/');// Returns: '/tmp/file'path.resolve('wwwroot','static_files/png/','../gif/image.gif');// If the current working directory is /home/myself/node,// this returns '/home/myself/node/wwwroot/static_files/gif/image.gif'
ATypeError
is thrown if any of the arguments is not a string.
path.sep
#
Provides the platform-specific path segment separator:
\
on Windows/
on POSIX
For example, on POSIX:
'foo/bar/baz'.split(path.sep);// Returns: ['foo', 'bar', 'baz']
On Windows:
'foo\\bar\\baz'.split(path.sep);// Returns: ['foo', 'bar', 'baz']
On Windows, both the forward slash (/
) and backward slash (\
) are acceptedas path segment separators; however, thepath
methods only add backwardslashes (\
).
path.toNamespacedPath(path)
#
On Windows systems only, returns an equivalentnamespace-prefixed path forthe givenpath
. Ifpath
is not a string,path
will be returned withoutmodifications.
This method is meaningful only on Windows systems. On POSIX systems, themethod is non-operational and always returnspath
without modifications.
path.win32
#
History
Version | Changes |
---|---|
v15.3.0 | Exposed as |
v0.11.15 | Added in: v0.11.15 |
Thepath.win32
property provides access to Windows-specific implementationsof thepath
methods.
The API is accessible viarequire('node:path').win32
orrequire('node:path/win32')
.