Node.js URL Module Tutorial

The Node.js URL module provides utilities for working with URLs, parsing, and formatting them.

In this beginner tutorial, you will learn URL module in Node and working with it.

Introduction to the URL Module

  1. The URL module in Node.js provides a way to work with URLs, which are common in web development.
  2. URLs include information about the protocol, domain, path, and query parameters.
  3. The URL module allows you to parse, format, and manipulate URLs easily.

Parsing URLs

  1. You can use the url.parse() method to parse a URL string into its components.
const url = require('url');

const urlString = 'https://www.example.com:8080/products?id=123#section';
const parsedUrl = url.parse(urlString, true);

console.log(parsedUrl);

/* 
Output: 
{
    protocol: 'https:',
    slashes: true,
    auth: null,
    host: 'www.example.com:8080',
    port: '8080',
    hostname: 'www.example.com',
    hash: '#section',
    search: '?id=123',
    query: { id: '123' },
    pathname: '/products',
    path: '/products?id=123',
    href: 'https://www.example.com:8080/products?id=123#section'
  }
*/  
    

Formatting URLs:

  1. The url.format() method allows you to convert URL components back into a formatted URL string.
const url = require('url');

const urlObject = {
    protocol: 'https:',
    host: 'www.example.com:8080',
    pathname: '/products',
    search: '?id=123',
    hash: '#section',
};

const formattedUrl = url.format(urlObject);

console.log(formattedUrl);

// Output: https://www.example.com:8080/products?id=123#section
    

Modifying URLs

  1. You can modify URL components and create new URLs using the URL class.
const { URL } = require('url');

const originalUrl = new URL('https://www.example.com/products?id=123');
originalUrl.searchParams.set('id', '456');

console.log(originalUrl.href);

// Output: https://www.example.com/products?id=456
    

Resolving URLs

  1. You can resolve a relative URL against a base URL using the url.resolve() method.
const url = require('url');

const baseUrl = 'https://www.example.com/';
const relativeUrl = 'products?id=123';
const resolvedUrl = url.resolve(baseUrl, relativeUrl);

console.log(resolvedUrl);

// Output: https://www.example.com/products?id=123