The URL module in NodeJS allows you to interact with URLs and their components. This module is part of NodeJS’s standard library, therefore it may be used without any further installs.
URL parsing
Parsing URLs is one of the most prevalent use cases for the URL module. The url.parse() function may be used to parse a URL. The method only accepts one argument: the URL string to be parsed. The function returns an object containing the protocol, hostname, port, path, and query attributes of the URL.
Example:
const url = require('url');
const exampleUrl = 'https://www.example.com:8080/path?key=value#hash';
const parsedUrl = url.parse(exampleUrl);
console.log(parsedUrl);
In this example, we first need the url module and then parse the URL string ‘https://www.example.com:8080/path?key=value#hash’ using the url.parse() function. The parsing result is saved in the parsedUrl variable and reported to the console.
Formatting URLs
The URL module also allows you to format a URL. The url.format() function may be used to format a URL. The method accepts a single argument: an object containing the different URL components.
Example:
const url = require('url');
const exampleUrl = {
protocol: 'https:',
hostname: 'www.example.com',
port: '8080',
pathname: '/path',
query: { key: 'value' },
hash: 'hash'
};
const formattedUrl = url.format(exampleUrl);
console.log(formattedUrl);
In this example, we first require the url
module and then use the url.format()
method to format the URL object exampleUrl
. The result of the formatting is stored in the formattedUrl
variable and logged to the console.
Q&A
Q: Can the URL module be used to perform network requests?
A: No, the URL module is used only for working with URLs and their components. For performing network requests, you should use a library such as the http
or https
module in NodeJS.
Exercises
- Write a NodeJS script that parses a URL and extracts its protocol, hostname, and path.
- Write a NodeJS script that formats a URL using the protocol, hostname, and path obtained in exercise 1.
Answers
1.
const url = require('url');
const exampleUrl = 'https://www.example.com:8080/path?key=value#hash';
const parsedUrl = url.parse(exampleUrl);
const protocol = parsedUrl.protocol;
const hostname = parsedUrl.hostname;
const path = parsedUrl.path;
console.log(protocol, hostname, path);
2.
const url = require('url');
const protocol = 'https:';
const hostname = 'www.example.com';
const path = '/path';
const formattedUrl = url.format({ protocol,