renatoargh renatoargh - 3 months ago 51
Node.js Question

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

Is this safe to use

to concatenate urls, for example:

require("path").join("", "ok");
//returns ''

require("path").join("", "ok");
//returns ''

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('', '/one')    // ''
url.resolve('', '/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".