path.resolve和path.join调用之间的区别? [英] Difference between path.resolve and path.join invocation?

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

问题描述

以下调用之间有区别吗?

Is there some difference between the following invocations?

path.join(__dirname, 'app')

vs.

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天全站免登陆