URL & URLSearchParams
WHATWG URL parsing, query-string building, and route matching — the natural companions to fetch() for the REST-client priority. URL is parsed by the URL Standard's own algorithm, written in TypeScript, as Node's ada implements it. URLSearchParams is an ordered list of pairs, live on its URL. URLPattern is the URL Pattern Standard, in TypeScript, as Node exposes it.
URL
ExactParses a URL, relative to an optional base, with the URL Standard's parser. Every component — href, origin, protocol, username, password, host, hostname, port, pathname, search, hash, searchParams — reads and (but origin) writes as the standard says, a setter running the parser from that component's state. A malformed URL throws Node's TypeError with code ERR_INVALID_URL; URL.parse returns null and URL.canParse false instead.
Parameters- urlstring
- The URL to parse (absolute, or relative when a base is given).
- basestring
- Optional base against which a relative url is resolved; an invalid base throws.
URL — The parsed URL with its component fields.
const u = new URL("https://example.com:8080/a/b?x=1&y=hello%20world#frag")
console.log(u.hostname) // example.com
console.log(new URL("/p", "http://h.com/a").href) // http://h.com/p- A default port is stripped and the host is lowercased (WHATWG normalization);
URL.parse/URL.canParsestatics andJSON.stringify(url)→href(toJSON) are supported - A non-ASCII hostname is case-folded and punycoded, without the rest of UTS 46's mapping: a full-width
EXAMPLE.compunycodes where Node readsexample.com
URLSearchParams
ExactReads and builds query strings. new URLSearchParams() starts empty; new URLSearchParams(init) parses a query string and tolerates a leading '?', so passing a URL's own .search straight through just works. Backed by an ordered name/value pair list (the WHATWG multi-value model), so duplicate keys and cross-key insertion order round-trip; get/set/has/delete/size/keys()/values()/entries()/forEach()/getAll()/sort() are all supported, plus toString() (application/x-www-form-urlencoded — a space is '+').
Parameters- initstring
- Optional query string to parse (a leading '?' is tolerated).
URLSearchParams — The parameter collection.
const params = new URLSearchParams()
params.set("q", "hello world")
params.set("page", "2")
console.log(params.toString()) // q=hello+world&page=2url.searchParamsis live: mutating it (append/set/delete/sort) re-serializes the query back intourl.search/url.href, matching the spec
URLPattern
Works, with caveatsWHATWG route matching, the URL Pattern Standard as Node's ada implements it. A pattern is a constructor string or an init object, optionally relative to a base URL; the full pattern grammar is supported (named and regexp groups, wildcards, {} groups, ? + * modifiers). test() and exec() take a URL string or an init object; exec() returns the standard's URLPatternResult, its groups in the order Node lists them. An invalid pattern throws a TypeError.
Parameters- inputstring | URLPatternInit
- A constructor string, or an init over protocol/username/password/hostname/port/pathname/search/hash/baseURL.
- baseURLstring
- The URL a relative pattern resolves against.
URLPattern — The compiled pattern.
const pattern = new URLPattern({ pathname: "/books/:id" })
console.log(pattern.test("https://example.com/books/123")) // true
const m = pattern.exec("https://example.com/books/123")
if (m !== null) { console.log(m.pathname.groups.id) } // 123- Regexp groups run on PCRE2: an empty optional group iteration reads
""(JavaScript:undefined),v-flag set operations never match, and invalidv-mode syntax is accepted
url.parse()
Works, with caveatsNode's legacy URL parser, the lib/url.js algorithm itself: lenient (never throws on a relative or odd input), null for an absent component, with slashes, backslash handling and auto-escaping. Returns a Url object with the legacy field names, distinct from the WHATWG URL; the first call prints Node's DEP0169 deprecation warning. Importable named, via namespace, or as the default of the url module.
Parameters- urlStringstring
- The URL to parse, absolute or relative.
- parseQueryStringboolean
- Parse query into an object with querystring.parse.
- slashesDenoteHostboolean
- Read //host/path as host and path.
Url — The legacy Url object.
import { parse } from 'url'
const u = parse('https://user:[email protected]:8080/a?x=1#h')
console.log(u.host) // example.com:8080
console.log(u.auth) // user:pw
console.log(u.query) // x=1
console.log(u.path) // /a?x=1- The parseQueryString object form of
queryis a dictionary: read it after narrowing;console.log/JSON.stringifyof it throughanydon't see its keys
url.format()
Exactlib/url.js's formatter: serializes a legacy Url object or a plain object with the legacy fields (query objects through querystring.stringify), parses and reformats a string, or serializes a WHATWG URL with the auth/fragment/search/unicode options.
Parameters- urlObjectUrl | URL | object
- The URL object to serialize.
string — The formatted URL string.
import { parse, format } from 'url'
const u = parse('https://a.com/x?q=1')
console.log(format(u)) // https://a.com/x?q=1url.fileURLToPath()
ExactConverts a file: URL (a string or WHATWG URL) into the percent-decoded filesystem path: a POSIX path, or a Windows drive path (file:///C:/dir/f → C:\dir\f) or UNC path when the URL has a host. { windows } picks the flavor on any host (undefined = the host's); a literal is resolved at compile time, a run-time boolean runs both halves. Throws on a non-file: scheme, an encoded / (or \ on win32), a non-absolute win32 path, and — on the POSIX flavor — a host other than empty/localhost, with Node's messages.
Parameters- urlstring | URL
- A file: URL.
- options{ windows?: boolean }
- Optional. true for the win32 form, false for POSIX, undefined for the host's.
string — The decoded path.
import { fileURLToPath } from 'url'
console.log(fileURLToPath('file:///foo%20bar')) // /foo bar
console.log(fileURLToPath('file:///C:/dir/f', { windows: true })) // C:\dir\furl.pathToFileURL()
ExactResolves a path to absolute, percent-encodes it (Node's escape set), and returns a WHATWG URL with the file: scheme; a Windows drive path is file:///C:/dir/f and a UNC path keeps its server as the host. { windows } picks the flavor on any host (undefined = the host's).
Parameters- pathstring
- A filesystem path.
- options{ windows?: boolean }
- Optional. true for the win32 form, false for POSIX, undefined for the host's.
URL — A file: URL.
import { pathToFileURL } from 'url'
console.log(pathToFileURL('/foo bar').href) // file:///foo%20bar
console.log(pathToFileURL('C:\\dir\\f', { windows: true }).href) // file:///C:/dir/furl.resolve()
Exactlib/url.js's resolution of a target against a base: relative paths, `.`/`..` segments, protocol-relative and cross-protocol targets, and non-slashed schemes like mailto:.
Parameters- fromstring
- The base URL.
- tostring
- The target to resolve.
string — The resolved URL.
import { resolve } from 'url'
console.log(resolve('http://a.com/x/', '../y')) // http://a.com/yurl.urlToHttpOptions()
Works, with caveatsRemaps a WHATWG URL into the option object http.request accepts (protocol, hostname, path, port, auth, ...).
Parameters- urlURL
- A WHATWG URL.
object — The http.request options.
import { urlToHttpOptions } from 'url'
const o = urlToHttpOptions(new URL('https://h:8443/p?a=1'))
console.log(o.path) // /p?a=1- Expects a WHATWG URL; a legacy Url/plain object isn't accepted
url.domainToASCII() / domainToUnicode()
Works, with caveatsPunycode/IDN conversion of a domain. Returns '' on failure, matching Node.
Parameters- domainstring
- The domain to convert.
string — The converted domain, or ''.
import { domainToASCII } from 'url'
console.log(domainToASCII('example.com')) // example.com- A non-ASCII domain is lowercased and punycoded without the rest of UTS 46's mapping: a full-width
EXAMPLE.compunycodes where Node readsexample.com