API reference

URL & URLSearchParams

10/10Coverage5/10Strict (zero caveats)

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.

Exact Works, with caveats Not supported

URL

Exact
new URL(url: string, base?: string): URL

Parses 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.
Returns

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
See it in a full example →
⚠ Differences from standard
  • A default port is stripped and the host is lowercased (WHATWG normalization); URL.parse/URL.canParse statics and JSON.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.com punycodes where Node reads example.com

URLSearchParams

Exact
new URLSearchParams(init?: string): URLSearchParams

Reads 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).
Returns

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=2
See it in a full example →
⚠ Differences from standard
  • url.searchParams is live: mutating it (append/set/delete/sort) re-serializes the query back into url.search/url.href, matching the spec

URLPattern

Works, with caveats
new URLPattern(input?: string | URLPatternInit, baseURL?: string, options?: { ignoreCase?: boolean }): URLPattern

WHATWG 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.
Returns

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
See it in a full example →
⚠ Differences from standard
  • Regexp groups run on PCRE2: an empty optional group iteration reads "" (JavaScript: undefined), v-flag set operations never match, and invalid v-mode syntax is accepted

url.parse()

Works, with caveats
url.parse(urlString: string, parseQueryString?: boolean, slashesDenoteHost?: boolean): Url

Node'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.
Returns

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
⚠ Differences from standard
  • The parseQueryString object form of query is a dictionary: read it after narrowing; console.log/JSON.stringify of it through any don't see its keys

url.format()

Exact
url.format(urlObject: URL | UrlObject | string, options?: URLFormatOptions): string

lib/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.
Returns

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=1

url.fileURLToPath()

Exact
url.fileURLToPath(url: string | URL, options?: { windows?: boolean }): string

Converts 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.
Returns

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\f

url.pathToFileURL()

Exact
url.pathToFileURL(path: string, options?: { windows?: boolean }): URL

Resolves 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.
Returns

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/f

url.resolve()

Exact
url.resolve(from: string, to: string): string

lib/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.
Returns

string — The resolved URL.

import { resolve } from 'url'
console.log(resolve('http://a.com/x/', '../y')) // http://a.com/y

url.urlToHttpOptions()

Works, with caveats
url.urlToHttpOptions(url: URL): HttpOptions

Remaps a WHATWG URL into the option object http.request accepts (protocol, hostname, path, port, auth, ...).

Parameters
urlURL
A WHATWG URL.
Returns

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
⚠ Differences from standard
  • Expects a WHATWG URL; a legacy Url/plain object isn't accepted

url.domainToASCII() / domainToUnicode()

Works, with caveats
url.domainToASCII(domain: string): string

Punycode/IDN conversion of a domain. Returns '' on failure, matching Node.

Parameters
domainstring
The domain to convert.
Returns

string — The converted domain, or ''.

import { domainToASCII } from 'url'
console.log(domainToASCII('example.com')) // example.com
⚠ Differences from standard
  • A non-ASCII domain is lowercased and punycoded without the rest of UTS 46's mapping: a full-width EXAMPLE.com punycodes where Node reads example.com