DEV Community

miku86
miku86

Posted on • Edited on

NodeJS: How To Use The URL Module

Intro

So we installed NodeJS on our machine.

We also know how to use commandline arguments.

Now we want to learn how to process an url from the commandline by using the URL module.

Write a simple script

  • Open your terminal
  • Create a file named index.js:
touch index.js
Enter fullscreen mode Exit fullscreen mode
  • Add this JavaScript code into it:
const url = require('url');

const myUrl = process.argv[2];

if (myUrl) {
  const { href, host, pathname, protocol } = new URL(myUrl);

  console.log(`The HREF is: ${href}`);
  console.log(`The Protocol is: ${protocol}`);
  console.log(`The Host is: ${host}`);
  console.log(`The Pathname is: ${pathname}`);
}

Enter fullscreen mode Exit fullscreen mode

Note: I use the most used url properties to decrease the complexity of this simple example. To see all the available properties, read the docs of the URL module.


Every line explained

// import the url module
const url = require('url');

// read the third argument (= the url ) & save it into a variable
const myUrl = process.argv[2];

// only run this block if the user inputs a third argument
if (myUrl) {
// destructure these specific properties from the URL
  const { href, host, pathname, protocol } = new URL(myUrl);

// log the destructured properties
  console.log(`The Href is: ${href}`);
  console.log(`The Protocol is: ${protocol}`);
  console.log(`The Host is: ${host}`);
  console.log(`The Pathname is: ${pathname}`);
}
Enter fullscreen mode Exit fullscreen mode

Sometimes you can see the usage of url.parse() from the Legacy URL API. The Legacy URL API is deprecated, don't use url.parse(), use new URL().


Run it from the terminal

  • Run it:
node index.js https://miku86.com/articles
Enter fullscreen mode Exit fullscreen mode
  • Result:
The Href is: https://miku86.com/articles
The Protocol is: https:
The Host is: miku86.com
The Pathname is: /articles
Enter fullscreen mode Exit fullscreen mode

Further Reading


Questions

  • Do you use the native URL module or some libraries like query-string? Why do you use it?

Top comments (0)