While /
is used as a file path delimiter on Unix (/file/to/path
), \
is
used on Windows instead (\file\to\path
).
The path delimiter can be retrieved with
path.sep
.
Windows actually allows using or mixing in /
delimiters in file paths
sometimes, but not always so this should not be relied on.
Absolute paths always start with /
on Unix, but on Windows they can take
many shapes:
\
: the current drive.C:\
: a specific drive (hereC:
). This can also be used with relative paths likeC:file\to\path
.\\HOST\
: UNC path, for remote hosts.\\?\
: allows to overcome file path length limit of 260 characters. Those can be produced in Node.js withpath.toNamespacedPath()
.\\.\
: device path.
When file paths are used as arguments to Node.js core methods:
- only Unix paths are allowed on Unix.
- both Unix and Windows paths are allowed on Windows (including mixed).
This includes arguments to
require(path)
,
import(path)
,
import from "path"
,
fs.*(path)
methods,
path.*()
methods or
process.chdir(path)
.
When file paths are returned by Node.js core methods:
- Unix paths are returned on Unix.
- Windows paths are returned on Windows.
This includes the return values of
path.*()
methods,
process.cwd()
,
os.homedir()
,
os.tmpdir()
,
os.devNull()
or the value of
__dirname
,
process.argv
and
process.execPath
.
Exceptions:
- using
path.win32.*()
orpath.posix.*()
instead ofpath.*()
will return Windows or Unix paths. - methods where the path is present both as argument and as return value depend
on whether the input path is Windows-like or Unix-like. This includes
fs.createReadStream()
andfs.mkdtemp()
.
Outside of Node.js, i.e. when the path is input from (or output to) the terminal or a file, its syntax is OS-specific.
- if a path must be output outside of Node.js (e.g. terminal or file),
path.normalize()
should be used to make it OS-specific. - if a path comes from outside of Node.js or from a core method, it will be OS-specific. However all Node.js core methods will properly handle it.
- in all other cases using Unix paths will just work.
ES modules require using
import.meta.url
,
import.meta.filename
and
import.meta.dirname
instead of __filename
and __dirname
.
import.meta.url
is a file:///...
URL. For backward compatibility, you
should:
- If possible, use the
file:///...
URL without converting it to a file path. Most Node.js core methods ( including all thefs
methods) support those URLs. - If using Node.js
>= 21.2.0
, useimport.meta.filename
andimport.meta.dirname
. - Otherwise, convert the URL using
url.fileURLToPath()
, as opposed to usingURL.pathname
. This will ensure the file path is valid on Windows.
Use
path.normalize()
when writing a file path to a terminal or file. Otherwise use Unix paths
(slashes).
Use
url.fileURLToPath()
with import.meta.url
.