
Url Module in NodeJs
The url
module in Node.js is used to parse and manipulate URLs. It comes built-in, so you donβt need to install anything.
π§ How to Use the URL Module
β Importing the module
const url = require('url');
π¦ Example: Parsing a URL
const url = require('url');const myURL = 'https://example.com:8080/path/name?query=123#section';const parsed = url.parse(myURL, true); // `true` parses query string into an objectconsole.log(parsed.hostname); // example.comconsole.log(parsed.pathname); // /path/nameconsole.log(parsed.port); // 8080console.log(parsed.query); // { query: '123' }console.log(parsed.hash); // #section
π Newer Way (WHATWG URL API)
Node.js also supports the newer URL
class (preferred for newer code):
const { URL } = require('url');const myURL = new URL('https://example.com:8080/path/name?query=123#section');console.log(myURL.hostname); // example.comconsole.log(myURL.pathname); // /path/nameconsole.log(myURL.port); // 8080console.log(myURL.searchParams.get('query')); // 123console.log(myURL.hash); // #section
π Modifying URLs
myURL.pathname = '/newpath';myURL.searchParams.set('page', '2');console.log(myURL.href); // https://example.com:8080/newpath?query=123&page=2#section
π§ Use Cases
Parse incoming request URLs in a web server.
Modify and build query strings.
Redirect URLs dynamically.
Extract data from URL parameters.