ThomasReggi
ThomasReggi

Reputation: 59505

How to edit URL using Node's new URL constructor?

I'm using a new version of Node.js that has a new way to parse URLs. Rather than url.parse you call new URL().

The one issue I am having is how to parse and update/manipulate the URL.

For instance with the old url.parse I could do this:

const p = url.parse('http://example.com')
const edits = {...p, protocol: 'https'}
const np = url.format(edits)

This is an example where I'm changing the schema of a URL.

This would be done using the new API as follows:

const p = new URL('http://example.com')

However this trick doesn't seem to be possible with the new URL, which returns a SYMBOL, so spreading the new value of p doesn't work. To make matters worse, some of the properties of p are readonly, which is interesting, and means I can't assign the value directly.

There is a .toJSON() method in the instance, which ironically doesn't provide JSON values of the parsed URL, but a string version of the assembled URL.

I am curious how to edit and reassemble a URL with the new Node URL API.

Upvotes: 1

Views: 2198

Answers (1)

ThomasReggi
ThomasReggi

Reputation: 59505

I was surprised to find out not all the properties are readonly, and the searchParams parameter has a setter.

const host = 'https://connect.stripe.com'
const clientId = config.get('STRIPE_CLIENT_ID')
const parsedUrl = new URL('/oauth/authorize', host)
parsedUrl.searchParams.set('scope', 'read_write')
parsedUrl.searchParams.set('client_id', clientId)
parsedUrl.searchParams.set('response_type', 'code')
console.log(parsedUrl.toString())

Upvotes: 2

Related Questions