URL Module in Node Js

  • The `url` module in Node.js provides utilities for parsing and formatting URLs. It allows you to work with URLs, extract different components (such as protocol, host, pathname, query parameters, etc.), and construct URLs. Below, I'll explain some of the common methods provided by the `url` module with examples.
Parsing a URL:
  • You can use the `url.parse()` method to parse a URL string into an object.


    const url = require('url');

    const urlString = 'https://www.example.com/path?name=John&age=30';
    const parsedUrl = url.parse(urlString, true); // The second parameter 'true' parses the query string

    console.log('Parsed URL:', parsedUrl);
    console.log('Protocol:', parsedUrl.protocol);
    console.log('Host:', parsedUrl.host);
    console.log('Path:', parsedUrl.pathname);
    console.log('Query:', parsedUrl.query);

    /*

    Output:
    ------

    Parsed URL: Url {
        protocol: 'https:',
        slashes: true,
        auth: null,
        host: 'www.example.com',
        port: null,
        hostname: 'www.example.com',
        hash: null,
        search: '?name=John&age=30',
        query: [Object: null prototype] { name: 'John', age: '30' },
        pathname: '/path',
        path: '/path?name=John&age=30',
        href: 'https://www.example.com/path?name=John&age=30'
    }
    Protocol: https:
    Host: www.example.com
    Path: /path
    Query: [Object: null prototype] { name: 'John', age: '30' }

    */

Formatting a URL:

  • The `url.format()` method allows you to construct a URL from an object.


    const url = require('url');

    const urlObject = {
        protocol: 'https',
        host: 'www.example.com',
        pathname: '/path',
        query: { name: 'John', age: 30 },
    };

    const formattedUrl = url.format(urlObject);
    console.log('Formatted URL:', formattedUrl);
    // Formatted URL: https://www.example.com/path?name=John&age=30

Resolving URLs:

  • The `url.resolve()` method resolves a given base URL and a relative URL into an absolute URL.


    const url = require('url');

    const baseUrl = 'https://www.example.com/path/';
    const relativeUrl = 'subpath';

    const resolvedUrl = url.resolve(baseUrl, relativeUrl);
    console.log('Resolved URL:', resolvedUrl);
    // Resolved URL: https://www.example.com/path/subpath

URL Object Properties:

  • The parsed URL object obtained from `url.parse()` has several properties:
    • `protocol`: The URL protocol (e.g., 'https:').
    • `slashes`: A boolean indicating whether the protocol requires slashes (e.g., `true` for 'https:').
    • `auth`: The authentication information.
    • `host`: The full host portion of the URL (including port if specified).
    • `port`: The port number if specified.
    • `hostname`: The host name (excluding port).
    • `hash`: The URL fragment identifier.
    • `search`: The query string including the leading "?".
    • `query`: The parsed query string as an object.
    • `pathname`: The path portion of the URL.
    • `path`: The full path including both pathname and search.
    • `href`: The original URL string.
Example:


    const url = require('url');

    const urlString = 'https://www.example.com:8080/path?name=John&age=30#section';
    const parsedUrl = url.parse(urlString, true);

    console.log('Parsed URL:', parsedUrl);
    console.log('Protocol:', parsedUrl.protocol);
    console.log('Host:', parsedUrl.host);
    console.log('Pathname:', parsedUrl.pathname);
    console.log('Query:', parsedUrl.query);
    console.log('Hash:', parsedUrl.hash);

    /*

    Output:
    ------

    Parsed URL: Url {
        protocol: 'https:',
        slashes: true,
        auth: null,
        host: 'www.example.com:8080',
        port: '8080',
        hostname: 'www.example.com',
        hash: '#section',
        search: '?name=John&age=30',
        query: [Object: null prototype] { name: 'John', age: '30' },
        pathname: '/path',
        path: '/path?name=John&age=30',
        href: 'https://www.example.com:8080/path?name=John&age=30#section'
    }
    Protocol: https:
    Host: www.example.com:8080
    Pathname: /path
    Query: [Object: null prototype] { name: 'John', age: '30' }
    Hash: #section

    */

  • The `url` module is particularly useful when working with web-related tasks in Node.js, such as handling URLs in web servers or parsing query parameters. Understanding how to parse, format, and manipulate URLs is crucial for many web development scenarios.

No comments:

Post a Comment