Node.js
/Beginner
URL Module
Definition
A core module providing utilities for URL resolution and parsing. It breaks down a full web address into readable, manageable pieces.
Explain Like I'm New
If someone hands you `https://google.com:8080/search?q=cats&sort=new`, trying to manually split that string to find the search term is a nightmare. The URL module instantly dissects it into neat pieces: the protocol (https), hostname (google.com), port (8080), path (/search), and search parameters (q=cats).
Real World Example
Reading the `?sort=desc&page=2` query parameters from an incoming request in a Node server so you know how to query your database.
Common Use Cases
- •Parsing incoming HTTP requests
- •Building URL strings dynamically
- •Extracting query parameters
Terminal Output
bash / terminal
// We do NOT need to require('url') anymore. 'URL' is global!
const testUrl = 'https://mysite.com:8080/products/shoes?color=red&size=10#reviews';
// Create a URL object
const parsed = new URL(testUrl);
console.log("Hostname:", parsed.hostname); // 'mysite.com'
console.log("Pathname:", parsed.pathname); // '/products/shoes'
console.log("Port:", parsed.port); // '8080'
console.log("Hash:", parsed.hash); // '#reviews'
// The magic of URLSearchParams (parsing the ? query string)
const color = parsed.searchParams.get('color');
console.log("Color Query:", color); // 'red'
// You can also easily build URLs!
parsed.searchParams.append('discount', 'true');
console.log("New URL:", parsed.toString());
// https://mysite.com:8080/products/shoes?color=red&size=10&discount=true#reviews
Interview Questions
basic
- What global class is used in modern Node to parse URLs?
intermediate
- How do you easily grab the value of `?user_id=123` from a URL?
advanced
- Why is the old `url.parse()` method deprecated?