Node.js url Module

In this tutorial, we are going to discuss about the Node.js “url” module. The Node.js url module, which provides utilities for working with URLs (Uniform Resource Locators). Here we’ll explore the functionalities of the “url” module, understand how it aids developers in handling URLs, and demonstrate practical use cases.

Use of Node.js url Module

In order to use this module, you have import “url” in your script.

const url = require("url");
//or
import url from "url";

Parsing URLs: “url.parse()”

The url.parse() method is used for dissecting a URL into its constituent parts. It returns an object containing properties such as protocol, hostname, pathname, and more.

const url = require("url");
const urlString = "https://www.example.com/path?query=parameter";
const parsedUrl = url.parse(urlString, true);

console.log("Parsed URL:", parsedUrl);

Result:

Parsed URL: Url {
  protocol: 'https:',
  slashes: true,
  auth: null,
  host: 'www.example.com',
  port: null,
  hostname: 'www.example.com',
  hash: null,
  search: '?query=parameter',
  query: [Object: null prototype] { query: 'parameter' },
  pathname: '/path',
  path: '/path?query=parameter',
  href: 'https://www.example.com/path?query=parameter'
}

The true argument in the url.parse(urlString, true) instructs the parser to populate the query property with an object representing the URL’s query parameters.

Formatting URLs: “url.format()”

Conversely, the url.format() method transforms a parsed URL object back into a formatted URL string. This is useful when you need to construct URLs dynamically.

const url = require("url");
const formattedUrl = url.format({
    protocol: "https",
    host: "www.example.com",
    pathname: "/path",
    query: { query: "parameter" },
});

console.log("Formatted URL:", formattedUrl);
// Output: Formatted URL: https://www.example.com/path?query=parameter

Resolving URLs: “url.resolve()”

When working with relative URLs, the url.resolve() method proves handy. It resolves a target URL relative to a base URL, providing a complete and absolute URL.

const url = require("url");
const baseUrl = "https://www.example.com";
const relativePath = "/path";
const resolvedUrl = url.resolve(baseUrl, relativePath);

console.log("Resolved URL:", resolvedUrl);
// Output: Resolved URL: https://www.example.com/path

Parsing Query Parameters:

Parsing query parameters from a URL is a common task. With the url.parse() method, you can easily extract and work with query parameters.

const url = require("url");
const queryString = "https://www.example.com/path?name=John&age=30";
const parsedUrl = url.parse(queryString, true);

console.log("Name:", parsedUrl.query.name);
console.log("Age:", parsedUrl.query.age);
/**
 * Output:
 * Name: John
 * Age: 30
 */