What's the difference between path.resolve and path.join?

前端 未结 3 1231
無奈伤痛
無奈伤痛 2020-12-12 09:02

Is there some difference between the following invocations?

path.join(__dirname, \'app\')

vs.

path.resolve(__dirname, \'app         


        
3条回答
  •  生来不讨喜
    2020-12-12 09:45

    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'
    

    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?

    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.

提交回复
热议问题