url
The url
module provides utilities for URL resolution and parsing. Modern code should use the WHATWG URL API.
API Surface
WHATWG URL
new URL(input[, base])
— create URL object.- Properties:
href
,protocol
,username
,password
,host
,hostname
,port
,pathname
,search
,hash
. url.searchParams
: interface to manage query params..get(name)
,.set(name, value)
,.append(name, value)
,.delete(name)
.
Legacy API
url.parse(urlStr)
— parse into object.url.format(obj)
— format object into string.url.resolve(from, to)
— resolve relative URL.
Examples (English only)
const { URL } = require("url");
// Modern URL API
const myUrl = new URL("https://user:[email protected]:8080/p/a/t/h?query=1#hash");
console.log(myUrl.hostname); // example.com
console.log(myUrl.pathname); // /p/a/t/h
console.log(myUrl.searchParams.get("query")); // 1
myUrl.searchParams.set("query", "42");
console.log(myUrl.toString());
// Legacy API
const url = require("url");
const parsed = url.parse("https://example.com/foo/bar?x=1");
console.log(parsed.hostname, parsed.pathname);
Notes
- Prefer WHATWG URL for consistency with browsers.
searchParams
provides convenient query manipulation.- Legacy API still works but is discouraged for new code.
- Always provide a base URL when parsing relative URLs.