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

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.

Leave a Comment