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

给定的路径序列会从右到左进行处理,后面的每个 path 会被追加到前面,直到构造出绝对路径。 例如,给定的路径片段序列:/目录1/目录2目录3,调用 path.resolve('/目录1', '/目录2', '目录3') 会返回 /目录2/目录3,因为 '目录3' 不是绝对路径,但 '/目录2' + '/' + '目录3' 是。

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


零长度的 path 片段会被忽略。

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

path.resolve('/目录1/目录2', './目录3');
// 返回: '/目录1/目录2/目录3'

path.resolve('/目录1/目录2', '/目录3/目录4/');
// 返回: '/目录3/目录4'

path.resolve('目录1', '目录2/目录3/', '../目录4/文件.gif');
// 如果当前工作目录是 /目录A/目录B,
// 则返回 '/目录A/目录B/目录1/目录2/目录4/文件.gif'

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

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

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.

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.

Zero-length path segments are ignored.

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'

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