node.jsurlstring-concatenation

Can I use require("path").join to safely concatenate urls?


Is this safe to use require("path").join to concatenate URLs, for example:

require("path").join("http://example.com", "ok"); 
//returns 'http://example.com/ok'

require("path").join("http://example.com/", "ok"); 
//returns 'http://example.com/ok'

If not, what way would you suggest for doing this without writing code full of ifs?


Solution

  • No. path.join() will return incorrect values when used with URLs.

    It sounds like you want new URL(). From the WHATWG URL Standard:

    new URL('/one', 'http://example.com/').href    // 'http://example.com/one'
    new URL('/two', 'http://example.com/one').href // 'http://example.com/two'
    

    Note that url.resolve is now marked as deprecated in the Node docs.

    As Andreas correctly points out in a comment, url.resolve (also deprecated) would only help if the problem is as simple as the example. url.parse also applies to this question because it returns consistently and predictably formatted fields via the URL object that reduces the need for "code full of ifs". However, new URL() is also the replacement for url.parse.