使用__dirname的path.join与path.resolve [英] path.join vs path.resolve with __dirname

查看:492
本文介绍了使用__dirname的path.join与path.resolve的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

同时使用 path.joinpath.resolve__dirname来解析Node.js中的绝对路径时是否存在差异?

Is there a difference when using both path.join and path.resolve with __dirname for resolving absolute path in Node.js?

像这样使用时,其中一个应该是首选(绝对路径分辨率为用例的90%)?

Should one of them be preferred when being used like that (absolute path resolutions are 90% of use cases)?

const absolutePath = path.join(__dirname, some, dir);

vs.

const absolutePath = path.resolve(__dirname, some, dir);

这两种方法都会规范路径.

Both methods normalize path.

这不是此问题的副本因为接受的答案是错误的.

This is not a duplicate of this question because the accepted answer is wrong.

推荐答案

是的,功能之间存在差异,但是在这种情况下,使用它们的方式将导致相同的结果.

Yes there is a difference between the functions but the way you are using them in this case will result in the same outcome.

path.join通过将两个路径合并在一起来返回规范化路径.它可以返回绝对路径,但不一定总是这样.

path.join returns a normalized path by merging two paths together. It can return an absolute path, but it doesn't necessarily always do so.

例如:

path.join('app/libs/oauth', '/../ssl')

解析为app/libs/ssl

path.resolve将解析为绝对路径.

例如,当您运行时:

path.resolve('bar', '/foo');

返回的路径将为/foo,因为这是可以构造的第一个绝对路径.

The path returned will be /foo since that is the first absolute path that can be constructed.

但是,如果您运行:

path.resolve('/bar/bae', '/foo', 'test');

返回的路径将再次为/foo/test,因为这是可以从右到左形成的第一个绝对路径.

The path returned will be /foo/test again because that is the first absolute path that can be formed from right to left.

如果不提供指定根目录的路径,则给resolve函数提供的路径将附加到当前工作目录.因此,如果您的工作目录为/home/mark/project/:

If you don't provide a path that specifies the root directory then the paths given to the resolve function are appended to the current working directory. So if your working directory was /home/mark/project/:

path.resolve('test', 'directory', '../back');

解析为

/home/mark/project/test/back

使用__dirname是包含源文件的目录的绝对路径.使用path.resolvepath.join时,如果在__dirname之后给出相同的路径,它们将返回相同的结果.在这种情况下,这实际上只是一个偏好问题.

Using __dirname is the absolute path to the directory containing the source file. When you use path.resolve or path.join they will return the same result if you give the same path following __dirname. In such cases it's really just a matter of preference.

这篇关于使用__dirname的path.join与path.resolve的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆