jdotjdot jdotjdot - 11 months ago 86
Node.js Question

Using path.join on NodeJS on Windows to create URL

I have two dynamic pieces of a URL that I'm trying to join together to make a full URL. Since I don't know the exact strings I'll be joining, I want to use a path-joining library to avoid string-joining errors like

, which has an extra slash, etc.

I am working on a Windows 7 Home computer using Node.js.

I tried using the
, but because I am on Windows, it turned all of the forward slashes backwards, which is obviously incorrect for a URL. Example:

var path = require('path'),
joined = path.join('http://www.mysite.com/', '/friends/family');

// Prints:
// http:\www.miserable.com\friends\family

What function or library can I use to join pieces of a URL together on Windows? Alternatively, how can I get
to force UNIX-style separators rather than those of Windows?

Answer Source

URLs aren't filesystem paths, so nothing in path is applicable to your requirements. I'd suggest using url.resolve() if it meets your needs, or url.format() if not. Note that you can't simply substitute either for path.join() in your code, since they require different arguments. Read the documentation carefully.