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.

It sounds like you want url.resolve. From the Node docs:

url.resolve('/one/two/three', 'four')         // '/one/two/four'
url.resolve('http://example.com/', '/one')    // 'http://example.com/one'
url.resolve('http://example.com/one', '/two') // 'http://example.com/two'

Edit: As Andreas correctly points out in a comment, url.resolve 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".

No! On Windows path.join will join with backslashes. HTTP urls are always forward slashes.

How about

> ["posts", "2013"].join("/")
'posts/2013'

When I tried PATH for concatenating url parts I run into problems. PATH.join stripes '//' down to '/' and this way invalidates an absolute url. (http://... -> http:/...) For me a quick fix was:

baseurl.replace(/\/$/,"") + '/' + path.replace(/^\//,"") )

or with the sollution posted by Colonel Panic:

[pathA.replace(/^\/|\/$/g,""),pathB.replace(/^\/|\/$/g,"")].join("/")

This is what I use:

function joinUrlElements() {
  var re1 = new RegExp('^\\/|\\/$','g'),
      elts = Array.prototype.slice.call(arguments);
  return elts.map(function(element){return element.replace(re1,""); }).join('/');
}

example:

url = joinUrlElements(config.mgmtServer, '/v1/o/', config.org, '/apps');