Node.js v20.11.1 文档


路径#

Path

稳定性: 2 - 稳定的

Stability: 2 - Stable

源代码: lib/path.js

node:path 模块提供了用于处理文件和目录的路径的实用工具。可以使用以下方式访问它:

The node:path module provides utilities for working with file and directory paths. It can be accessed using:

const path = require('node:path'); 

Windows 与 POSIX#

Windows vs. POSIX

node:path 模块的默认操作因运行 Node.js 应用的操作系统而异。具体来说,当在 Windows 操作系统上运行时,node:path 模块将假定正在使用 Windows 风格的路径。

The default operation of the node:path module varies based on the operating system on which a Node.js application is running. Specifically, when running on a Windows operating system, the node:path module will assume that Windows-style paths are being used.

因此,在 POSIX 和 Windows 上使用 path.basename() 可能会产生不同的结果:

So using path.basename() might yield different results on POSIX and Windows:

在 POSIX 上:

On POSIX:

path.basename('C:\\temp\\myfile.html');
// Returns: 'C:\\temp\\myfile.html' 

在 Windows 上:

On Windows:

path.basename('C:\\temp\\myfile.html');
// Returns: 'myfile.html' 

当使用 Windows 文件路径时,若要在任何操作系统上获得一致的结果,则使用 path.win32

To achieve consistent results when working with Windows file paths on any operating system, use path.win32:

在 POSIX 和 Windows 上:

On POSIX and Windows:

path.win32.basename('C:\\temp\\myfile.html');
// Returns: 'myfile.html' 

当使用 POSIX 文件路径时,若要在任何操作系统上获得一致的结果,则使用 path.posix

To achieve consistent results when working with POSIX file paths on any operating system, use path.posix:

在 POSIX 和 Windows 上:

On POSIX and Windows:

path.posix.basename('/tmp/myfile.html');
// Returns: 'myfile.html' 

在 Windows 上,Node.js 遵循独立驱动器工作目录的概念。当使用不带反斜杠的驱动器路径时,可以观察到此行为。例如,path.resolve('C:\\') 可能返回与 path.resolve('C:') 不同的结果。有关详细信息,请参阅 这个 MSDN 页面

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. For example, path.resolve('C:\\') can potentially return a different result than path.resolve('C:'). For more information, see this MSDN page.

path.basename(path[, suffix])#

path.basename() 方法返回 path 的最后一部分,类似于 Unix basename 命令。忽略尾随 目录分隔符

The path.basename() method returns the last portion of a path, similar to the Unix basename command. Trailing directory separators are ignored.

path.basename('/foo/bar/baz/asdf/quux.html');
// Returns: 'quux.html'

path.basename('/foo/bar/baz/asdf/quux.html', '.html');
// Returns: 'quux' 

尽管 Windows 通常以不区分大小写的方式处理文件名(包括文件扩展名),但此函数不会。例如,C:\\foo.htmlC:\\foo.HTML 指的是同一个文件,但 basename 将扩展名视为区分大小写的字符串:

Although Windows usually treats file names, including file extensions, in a case-insensitive manner, this function does not. For example, C:\\foo.html and C:\\foo.HTML refer to the same file, but basename treats the extension as a case-sensitive string:

path.win32.basename('C:\\foo.html', '.html');
// Returns: 'foo'

path.win32.basename('C:\\foo.HTML', '.html');
// Returns: 'foo.HTML' 

如果 path 不是字符串,或者如果给定 suffix 并且不是字符串,则抛出 TypeError

A TypeError is thrown if path is not a string or if suffix is given and is not a string.

path.delimiter#

提供特定于平台的路径定界符:

Provides the platform-specific path delimiter:

  • ; 用于 Windows

    ; for Windows

  • : 用于 POSIX

    : for POSIX

例如,在 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'] 

在 Windows 上:

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)#

path.dirname() 方法返回 path 的目录名,类似于 Unix dirname 命令。尾随的目录分隔符被忽略,见 path.sep

The path.dirname() method returns the directory name of a path, similar to the Unix dirname command. Trailing directory separators are ignored, see path.sep.

path.dirname('/foo/bar/baz/asdf/quux');
// Returns: '/foo/bar/baz/asdf' 

如果 path 不是字符串,则抛出 TypeError

A TypeError is thrown if path is not a string.

path.extname(path)#

path.extname() 方法返回 path 的扩展名,即 path 的最后一部分中从最后一次出现的 .(句点)字符到字符串的结尾。如果 path 的最后一部分中没有 .,或者除了 path 的基本名称(参见 path.basename())的第一个字符之外没有 . 个字符,则返回空字符串。

The path.extname() method returns the extension of the path, from the last occurrence of the . (period) character to end of string in the last portion of the path. If there is no . in the last portion of the path, or if there are no . characters other than the first character of the basename of path (see path.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' 

如果 path 不是字符串,则抛出 TypeError

A TypeError is thrown if path is not a string.

path.format(pathObject)#

path.format() 方法从对象返回路径字符串。这与 path.parse() 相反。

The path.format() method returns a path string from an object. This is the opposite of path.parse().

当向 pathObject 提供属性时,存在一个属性优先于另一个属性的组合:

When providing properties to the pathObject remember that there are combinations where one property has priority over another:

  • 如果提供 pathObject.dir,则忽略 pathObject.root

    pathObject.root is ignored if pathObject.dir is provided

  • 如果 pathObject.base 存在,则忽略 pathObject.extpathObject.name

    pathObject.ext and pathObject.name are ignored if pathObject.base exists

例如,在 POSIX 上:

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' 

在 Windows 上:

On Windows:

path.format({
  dir: 'C:\\path\\dir',
  base: 'file.txt',
});
// Returns: 'C:\\path\\dir\\file.txt' 

path.isAbsolute(path)#

path.isAbsolute() 方法确定 path 是否为绝对路径。

The path.isAbsolute() method determines if path is an absolute path.

如果给定的 path 是零长度字符串,则将返回 false

If the given path is a zero-length string, false will be returned.

例如,在 POSIX 上:

For example, on POSIX:

path.isAbsolute('/foo/bar'); // true
path.isAbsolute('/baz/..');  // true
path.isAbsolute('qux/');     // false
path.isAbsolute('.');        // false 

在 Windows 上:

On Windows:

path.isAbsolute('//server');    // true
path.isAbsolute('\\\\server');  // true
path.isAbsolute('C:/foo/..');   // true
path.isAbsolute('C:\\foo\\..'); // true
path.isAbsolute('bar\\baz');    // false
path.isAbsolute('bar/baz');     // false
path.isAbsolute('.');           // false 

如果 path 不是字符串,则抛出 TypeError

A TypeError is thrown if path is not a string.

path.join([...paths])#

path.join() 方法使用特定于平台的分隔符作为定界符将所有给定的 path 片段连接在一起,然后规范化生成的路径。

The path.join() method joins all given path segments together using the platform-specific separator as a delimiter, then normalizes the resulting path.

零长度的 path 片段被忽略。如果连接的路径字符串是零长度字符串,则将返回 '.',表示当前工作目录。

Zero-length path segments are ignored. If the joined path string is a zero-length string then '.' will be returned, representing the current working 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 {}' 

如果任何路径片段不是字符串,则抛出 TypeError

A TypeError is thrown if any of the path segments is not a string.

path.normalize(path)#

path.normalize() 方法规范化给定的 path,解析 '..''.' 片段。

The path.normalize() method normalizes the given path, resolving '..' and '.' segments.

当找到多个连续的路径片段分隔符(例如 POSIX 上的 / 和 Windows 上的 \/)时,则它们将被平台特定路径片段分隔符(POSIX 上的 / 和 Windows 上的 \)的单个实例替换。保留尾随的分隔符。

When multiple, sequential path segment separation characters are found (e.g. / on POSIX and either \ or / on Windows), they are replaced by a single instance of the platform-specific path segment separator (/ on POSIX and \ on Windows). Trailing separators are preserved.

如果 path 是零长度字符串,则返回 '.',表示当前工作目录。

If the path is a zero-length string, '.' is returned, representing the current working directory.

例如,在 POSIX 上:

For example, on POSIX:

path.normalize('/foo/bar//baz/asdf/quux/..');
// Returns: '/foo/bar/baz/asdf' 

在 Windows 上:

On Windows:

path.normalize('C:\\temp\\\\foo\\bar\\..\\');
// Returns: 'C:\\temp\\foo\\' 

由于 Windows 识别多个路径分隔符,两个分隔符都将被 Windows 首选分隔符 (\) 的实例替换:

Since Windows recognizes multiple path separators, both separators will be replaced by instances of the Windows preferred separator (\):

path.win32.normalize('C:////temp\\\\/\\/\\/foo/bar');
// Returns: 'C:\\temp\\foo\\bar' 

如果 path 不是字符串,则抛出 TypeError

A TypeError is thrown if path is not a string.

path.parse(path)#

path.parse() 方法返回一个对象,其属性表示 path 的重要元素。尾随的目录分隔符被忽略,见 path.sep

The path.parse() method returns an object whose properties represent significant elements of the path. Trailing directory separators are ignored, see path.sep.

返回的对象将具有以下属性:

The returned object will have the following properties:

例如,在 POSIX 上:

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.) 

在 Windows 上:

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.) 

如果 path 不是字符串,则抛出 TypeError

A TypeError is thrown if path is not a string.

path.posix#

path.posix 属性提供对 path 方法的 POSIX 特定实现的访问。

The path.posix property provides access to POSIX specific implementations of the path methods.

API 可通过 require('node:path').posixrequire('node:path/posix') 访问。

The API is accessible via require('node:path').posix or require('node:path/posix').

path.relative(from, to)#

path.relative() 方法根据当前工作目录返回从 fromto 的相对路径。如果 fromto 都解析为相同的路径(在分别调用 path.resolve() 之后),则返回零长度字符串。

The path.relative() method returns the relative path from from to to based on the current working directory. If from and to each resolve to the same path (after calling path.resolve() on each), a zero-length string is returned.

如果零长度字符串作为 fromto 传入,则将使用当前工作目录而不是零长度字符串。

If a zero-length string is passed as from or to, the current working directory will be used instead of the zero-length strings.

例如,在 POSIX 上:

For example, on POSIX:

path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb');
// Returns: '../../impl/bbb' 

在 Windows 上:

On Windows:

path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb');
// Returns: '..\\..\\impl\\bbb' 

如果 fromto 不是字符串,则抛出 TypeError

A TypeError is thrown if either from or to is not a string.

path.resolve([...paths])#

path.resolve() 方法将路径或路径片段的序列解析为绝对路径。

The path.resolve() method resolves a sequence of paths or path segments into an absolute path.

给定的路径序列从右到左处理,每个后续的 path 会被追加到前面,直到构建绝对路径。例如,给定路径段的顺序:/foo/barbaz,调用 path.resolve('/foo', '/bar', 'baz') 将返回 /bar/baz,因为 'baz' 不是绝对路径,但 '/bar' + '/' + 'baz' 是。

The given sequence of paths is processed from right to left, with each subsequent path prepended until an absolute path is constructed. For instance, given the sequence of path segments: /foo, /bar, baz, calling path.resolve('/foo', '/bar', 'baz') would return /bar/baz because 'baz' is not an absolute path but '/bar' + '/' + 'baz' is.

如果在处理完所有给定的 path 片段之后,还没有生成绝对路径,则使用当前工作目录。

If, after processing all given path segments, an absolute path has not yet been generated, the current working directory is used.

生成的路径被规范化,并删除尾部斜杠(除非路径解析为根目录)。

The resulting path is normalized and trailing slashes are removed unless the path is resolved to the root directory.

零长度的 path 片段被忽略。

Zero-length path segments are ignored.

如果没有传入 path 片段,则 path.resolve() 将返回当前工作目录的绝对路径。

If no path segments are passed, path.resolve() will return the absolute path of 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' 

如果任何参数不是字符串,则抛出 TypeError

A TypeError is thrown if any of the arguments is not a string.

path.sep#

提供特定于平台的路径片段分隔符:

Provides the platform-specific path segment separator:

  • Windows 上是 \

    \ on Windows

  • POSIX 上是 /

    / on POSIX

例如,在 POSIX 上:

For example, on POSIX:

'foo/bar/baz'.split(path.sep);
// Returns: ['foo', 'bar', 'baz'] 

在 Windows 上:

On Windows:

'foo\\bar\\baz'.split(path.sep);
// Returns: ['foo', 'bar', 'baz'] 

在 Windows 上,正斜杠 (/) 和反斜杠 (\) 都被接受为路径段分隔符;但是,path 方法仅添加反斜杠 (\)。

On Windows, both the forward slash (/) and backward slash (\) are accepted as path segment separators; however, the path methods only add backward slashes (\).

path.toNamespacedPath(path)#

仅在 Windows 系统上,返回给定 path 的等效 命名空间前缀路径。如果 path 不是字符串,则 path 将不加修改地返回。

On Windows systems only, returns an equivalent namespace-prefixed path for the given path. If path is not a string, path will be returned without modifications.

此方法仅在 Windows 系统上有意义。在 POSIX 系统上,该方法是不可操作的,并且始终返回 path 而不进行修改。

This method is meaningful only on Windows systems. On POSIX systems, the method is non-operational and always returns path without modifications.

path.win32#

path.win32 属性提供对 path 方法的 Windows 特定实现的访问。

The path.win32 property provides access to Windows-specific implementations of the path methods.

API 可通过 require('node:path').win32require('node:path/win32') 访问。

The API is accessible via require('node:path').win32 or require('node:path/win32').