Photo by James Harrison on Unsplash
Recently, in one of my projects, I had pieces of URLs and needed a function to concatenate them and construct a full URL.
Example of the full URL I would like to construct: https://github.com/weikangchia/gitcg
-
baseUrl: https://github.com
-
path1 (user of this repository): weikangchia
-
path2 (name of the repository): gitcg
Initially, I used the ES6 template literals method to construct my full URL.
However, I realized that this method was not safe. If any of my paths happened to include a slash, my fullUrl
would have a double slash and become an invalid URL.
After Googling for a while, I tried using 2 Node.js modules:
-
Url A module that provides utilities for URL resolution and parsing. It provides 2 APIs for working with URLs: a legacy API that is Node.js specific, and a newer API that implements the same WHATWG URL Standard used by web browsers.
-
Path A module that provides utilities for working with file and directory paths.
And, it worked! I feel that this approach is one of the safer ways to concatenate URLs with Node.js. This approach uses only the built-in modules in Node.js, so fewer jobs to deal with CVEs and maintenance for our production code.
And there we have it. I hope you have found this useful. Thank you for reading. If you enjoyed this article, remember to follow me for more updates!
Feel free to leave comments below if you think there are better ways to concatenate URLs with Node.js.