Node.js v18.20.8 文档


路径#>

【Path】

源代码: 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 使用 ;
  • 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.base,则会忽略 pathObject.extpathObject.name

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

在 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.】

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

【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 上使用 \
  • 在 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.】

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

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

Node.js 中文网 - 粤ICP备13048890号