1) What does the URL Module do?
1) Node JS 'url' module provides utilities for URL resolution and parsing.
2) It allows you to parse URLs into their components (such as protocol, hostname, port, path, hash, query parameters, and more) and format URL strings from these components.
3) To import the URL module in your application, use the require() method:
var url = require ('url');
2) URL Parse() method
url.parse() method can parse the address and returns a URL object with each part of the address as properties.
Example:
Example:
const url = require('url'); const urlString = 'https://example.com:8080/path?query=value'; const parsedUrl = url.parse(urlString, true); // Pass true as the second argument to parse query parameters console.log(parsedUrl); |
We can also print the hostname, pathname, and query as well-
console.log (parsedUrl.host); // returns example.com:8080
console.log (parsedUrl.pathname); // returns /path
console.log (parsedUrl.search); // returns ?query=value
3) URL Resolve() method
The url.resolve() method resolves a relative URL path against a base URL.
Example:
const url = require('url'); const baseUrl = 'https://example.com/users'; const relativePath = '/profile'; const resolvedUrl = url.resolve(baseUrl, relativePath); console.log(resolvedUrl); // returns https://example.com/profile |
No comments:
Post a Comment