How to use URL module in NodeJS

I. What is the URL module?

The URL module is quite similar to the Path module, but instead of handling the path, this module handles the current URL the user is accessing.

The OS module provides information about the computer’s operating system.

To include the OS module, we use the require() method:

const url = require("url");

II. URL String & URL Object

A URL string is made up of many small components, and by using URL module, we can process and retrieve those small components.

scheme://host:port/path?query

http://www.example.com:8000/software/index.html?id=10&status=active

We can use the URL() constructor to create a URL object and access the components.

const url = require("url");

const newUrl = new URL(
  "https://www.example.com:8000/software/index.html?q=abc"
);

// Serialized URL
console.log(newUrl.href);
console.log(newUrl.toString());

// Host (root domain)
console.log(newUrl.host);

// Hostname (No port)
console.log(newUrl.hostname);

// Port
console.log(newUrl.port);

// Pathname
console.log(newUrl.pathname);

// Serialized query
console.log(newUrl.search);

// Params object
console.log(newUrl.searchParams);

// Add param
newUrl.searchParams.append("status", "alive");
console.log(newUrl.searchParams);