path.resolve 和 path.join 有什么区别? [英] What's the difference between path.resolve and path.join?

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

问题描述

以下调用之间有什么区别吗?

Is there some difference between the following invocations?

path.join(__dirname, 'app')

对比

path.resolve(__dirname, 'app')

应该首选哪一个?

推荐答案

这两个函数以非常不同的方式处理以 / 开头的段;join 只会将其与前一个参数连接起来,但是 resolve 会将其视为根目录,并忽略所有先前的路径 - 将其视为执行 cd 每个参数:

The two functions deal with segments starting with / in very different ways; join will just concatenate it with the previous argument, however resolve will treat this as the root directory, and ignore all previous paths - think of it as the result of executing cd with each argument:

path.join('/a', '/b') // Outputs '/a/b'

path.resolve('/a', '/b') // Outputs '/b'

另一件需要注意的事情是 path.resolve 将始终产生绝对 URL,并将使用您的工作目录作为解析此路径的基础.但由于 __dirname 是绝对路径,无论如何这对您来说无关紧要.

Another thing to note is that path.resolve will always result in an absolute URL, and will use your working directory as a base to resolve this path. But as __dirname is an absolute path anyway this doesn't matter in your case.

至于您应该使用哪一个,答案是:这取决于您希望以 / 开头的段的行为方式 - 它们应该被简单地连接起来还是应该充当新的根?

As for which one you should use, the answer is: it depends on how you want segments starting in / to behave - should they be simply joined or should they act as the new root?

如果其他参数是硬编码的,那真的没有关系,在这种情况下,您可能应该考虑 (a) 此行将来可能会如何更改以及 (b) 它与代码中的其他地方的一致性如何.

If the other arguments are hard coded it really doesn't matter, in which case you should probably consider (a) how this line might change in future and (b) how consistent is it with other places in the code.

这篇关于path.resolve 和 path.join 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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