Now, with the version
7.10 of Node.js, you can now easily manage urls.
You can have the full documentation going to the official node.js website
Get what you want from an URL
Let’s try to create an
URL object and break it down.
And I have an amazing result, with a lots of usefull data.
As you can see it will really be easier, as I told you before I can now easily access the port on
There is also an object returned in
searchParams which is URLSearchParams.
In a nutshell this is how our url is split
Manage yours query parameters
As you saw before our
URL object is returning
This object also have usefull methods, for example if you want to check if a param exists you can use
myUrl.searchParams.has('query'), you can access a param with
myUrl.searchParams.get('query'). You have can read the full documentation in the node official website
What can we do with that?
Ok now we have an object to manage URLs with node but what can we do ? I suggest to code a small function which can generate urls with for our view.
Let’s define our function:
<string>link path to genrate our url, for example /forum
What are the results ?
What this code is doing ?
- first checking if there is a query param and set an empty object if no.
- Generate an
URLobject from the
- Generate an
URLSearchParamsobject, if the path already have query params, they are added to the object.
- loop on the
queryParamsto add them into the
- Finally return the result with the pathName from the
URLobject and if there is queryParams add them.
Now we have an amazing function to generate urls in our views !
I hope you liked this article and will use node.js url when you need it.
Let me know if you have questions or nice examples using node.js url.