m90
m90

Reputation: 11822

How do I change the port in a (legacy) URL object and stringify it?

I'm trying to change (or add) a port value in a given URL string in Node.js.

https://localhost:8080/index.html?query=value => https://localhost:9090/index.html?query=value

or

https://localhost/index.html?query=value => https://localhost:9090/index.html?query=value

Having to support Node 6 still, I am trying to use the legacy URL API like this:

> var parsed = url.parse('https://localhost:8080/index.html?query=value');
undefined
> parsed.port = '9090'
'9090'
> url.format(parsed)
'https://localhost:8080/index.html?query=value'

This seems to be due to the fact that url.format does the following:

Otherwise, if the urlObject.host property value is truthy, the value of urlObject.host is coerced to a string and appended to result.

Which led me to do the following:

> var parsed = url.parse('https://localhost:8080/index.html?query=value');
undefined
> delete parsed.host
true
> parsed.port = '9090'
'9090'
> url.format(parsed)
'https://localhost:9090/index.html?query=value'

which does what I want, but feels very hacky and I am unsure about possible side effects of doing that.

Is there a simpler and more idiomatic way of changing the port in a URL string without having to resort to Regexes and the likes?

Upvotes: 0

Views: 618

Answers (1)

Sam Denty
Sam Denty

Reputation: 4085

You could use the URL API - though it may not be supported on older versions of Node. For older versions you can use polyfills such as url-parse

Example:

var url = new URL("https://localhost:8080/index.html?query=value")
url.port = "9090"

var newUrl = url.toString()
// "https://localhost:9090/index.html?query=value

Upvotes: 1

Related Questions