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.
No.
path.join()
will return incorrect values when used with URLs.It sounds like you want
url.resolve
. From the Node docs: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 theURL
object that reduces the need for "code full of ifs".If you use Angular, you can use Location:
Works only on 2 arguments though, so you have to chain calls or write a helper function to do that if needed.
When I tried PATH for concatenating url parts I run into problems.
PATH.join
stripes '//' down to '/' and this way invalidates an absolute url (eg. http://... -> http:/...). For me a quick fix was:or with the solution posted by Colonel Panic:
Axios has a helper function that can combine URLs.
No! On Windows
path.join
will join with backslashes. HTTP urls are always forward slashes.How about
We do it like this: