Node.js — URL
Import URL Module
const { URL } = require('url');
Creating URLs
const url = new URL('https://example.com:8080/path?q=search#hash');
url.protocol // 'https:'
url.hostname // 'example.com'
url.port // '8080'
url.pathname // '/path'
url.search // '?q=search'
url.hash // '#hash'
url.origin // 'https://example.com:8080'
URL Search Params
const url = new URL('https://example.com?name=john&age=30');
url.searchParams.get('name') // 'john'
url.searchParams.get('age') // '30'
url.searchParams.set('city', 'NYC');
url.searchParams.append('hobby', 'reading');
url.searchParams.delete('age');
// Iterate params
url.searchParams.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
URL Parsing
const parsed = new URL('https://user:pass@example.com/path?q=1');
parsed.username // 'user'
parsed.password // 'pass'
parsed.host // 'example.com'
parsed.pathname // '/path'
Practical Example
function buildUrl(base, params) {
const url = new URL(base);
Object.entries(params).forEach(([key, val]) => {
url.searchParams.set(key, val);
});
return url.toString();
}
buildUrl('https://api.example.com/users', { page: 1, limit: 10 });
Mini Practice
- Parse a URL string
- Access URL components
- Manipulate search params
- Build a URL with parameters
Up Next
Continue with Events — event-driven programming.
Related Topics
Frequently Asked Questions about URL
What is URL in Node.js?
URL is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn URL?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn URL.
Why is URL important in Node.js?
URL is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.