URL() Method in Node.js
0 115
Working with web addresses often involves extracting or manipulating different components of a URL, like the hostname, query parameters, or path. Node.js makes this easier with the built-in URL
class. This article explores how the URL()
constructor helps parse and handle URLs effectively in a Node.js environment.
What is the URL() Constructor?
The URL()
method in Node.js is used to create a structured URL object from a given URL string. It belongs to the global URL
class and is a part of the url
module in Node.js. This object provides easy access to various URL components like protocol, host, pathname, search params, etc.
Syntax
new URL(input, base)
Parameters:
input
: The absolute URL or path to be parsed.base
(optional): A base URL to resolve relative URLs.
Basic Example
const { URL } = require('url');
const myURL = new URL('https://example.com/path?name=John&age=30');
console.log(myURL.hostname); // Output: example.com
console.log(myURL.pathname); // Output: /path
console.log(myURL.searchParams.get('name')); // Output: John
Here, the URL
object makes it simple to access specific parts of the address.
Using a Base URL
If you're working with relative URLs, you can pass a base URL as the second argument:
const relativeURL = new URL('/about', 'https://mysite.com');
console.log(relativeURL.href); // Output: https://mysite.com/about
Accessing URL Components
The URL
object provides properties like:
protocol
: e.g.,https:
host
: e.g.,example.com
pathname
: path of the resourcesearchParams
: an instance ofURLSearchParams
for query handling
Modifying a URL
You can also change parts of the URL easily:
myURL.pathname = '/contact';
myURL.searchParams.set('city', 'London');
console.log(myURL.href);
// Output: https://example.com/contact?name=John&age=30&city=London
Conclusion
The URL()
method in Node.js is a powerful and convenient way to dissect and construct URLs. Whether you’re building a server or handling HTTP requests, this method can save time and reduce complexity when dealing with URL strings.
If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!

Share:
Comments
Waiting for your comments