diff --git a/doc/api/url.md b/doc/api/url.md index 43402d634d5c60..06a5618949bf7f 100644 --- a/doc/api/url.md +++ b/doc/api/url.md @@ -15,568 +15,244 @@ A URL string is a structured string containing multiple meaningful components. When parsed, a URL object is returned containing properties for each of these components. -The following details each of the components of a parsed URL. The example -`'http://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash'` is used to -illustrate each. +The `url` module provides two APIs for working with URLs: a legacy API that is +Node.js specific, and a newer API that implements the same +[WHATWG URL Standard][] used by web browsers. + +*Note*: While the Legacy API has not been deprecated, it is maintained solely +for backwards compatibility with existing applications. New application code +should use the WHATWG API. + +A comparison between the WHATWG and Legacy APIs is provided below. Above the URL +`'http://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash'`, properties of +an object returned by the legacy `url.parse()` are shown. Below it are +properties of a WHATWG `URL` object. + +*Note*: WHATWG URL's `origin` property includes `protocol` and `host`, but not +`username` or `password`. ```txt -┌─────────────────────────────────────────────────────────────────────────────────┐ -│ href │ -├──────────┬┬───────────┬─────────────────────┬───────────────────────────┬───────┤ -│ protocol ││ auth │ host │ path │ hash │ -│ ││ ├──────────────┬──────┼──────────┬────────────────┤ │ -│ ││ │ hostname │ port │ pathname │ search │ │ -│ ││ │ │ │ ├─┬──────────────┤ │ -│ ││ │ │ │ │ │ query │ │ -" http: // user:pass @ sub.host.com : 8080 /p/a/t/h ? query=string #hash " -│ ││ │ │ │ │ │ │ │ -└──────────┴┴───────────┴──────────────┴──────┴──────────┴─┴──────────────┴───────┘ +┌─────────────────────────────────────────────────────────────────────────────────────────────┐ +│ href │ +├──────────┬──┬─────────────────────┬─────────────────────┬───────────────────────────┬───────┤ +│ protocol │ │ auth │ host │ path │ hash │ +│ │ │ ├──────────────┬──────┼──────────┬────────────────┤ │ +│ │ │ │ hostname │ port │ pathname │ search │ │ +│ │ │ │ │ │ ├─┬──────────────┤ │ +│ │ │ │ │ │ │ │ query │ │ +" https: // user : pass @ sub.host.com : 8080 /p/a/t/h ? query=string #hash " +│ │ │ │ │ hostname │ port │ │ │ │ +│ │ │ │ ├──────────────┴──────┤ │ │ │ +│ protocol │ │ username │ password │ host │ │ │ │ +├──────────┴──┼──────────┴──────────┼─────────────────────┤ │ │ │ +│ origin │ │ origin │ pathname │ search │ hash │ +├─────────────┴─────────────────────┴─────────────────────┴──────────┴────────────────┴───────┤ +│ href │ +└─────────────────────────────────────────────────────────────────────────────────────────────┘ (all spaces in the "" line should be ignored -- they are purely for formatting) ``` -### urlObject.auth +Parsing the URL string using the WHATWG API: -The `auth` property is the username and password portion of the URL, also -referred to as "userinfo". This string subset follows the `protocol` and -double slashes (if present) and precedes the `host` component, delimited by an -ASCII "at sign" (`@`). The format of the string is `{username}[:{password}]`, -with the `[:{password}]` portion being optional. +```js +const URL = require('url').URL; +const myURL = + new URL('https://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash'); +``` -For example: `'user:pass'` +*Note*: In Web Browsers, the WHATWG `URL` class is a global that is always +available. In Node.js, however, the `URL` class must be accessed via +`require('url').URL`. -### urlObject.hash +Parsing the URL string using the Legacy API: -The `hash` property consists of the "fragment" portion of the URL including -the leading ASCII hash (`#`) character. +```js +const url = require('url'); +const myURL = + url.parse('https://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash'); +``` -For example: `'#hash'` +## The WHATWG URL API + -### urlObject.host +*Note*: Using the `delete` keyword on `URL` objects (e.g. +`delete myURL.protocol`, `delete myURL.pathname`, etc) has no effect but will +still return `true`. -The `host` property is the full lower-cased host portion of the URL, including -the `port` if specified. +### Class: URL +#### Constructor: new URL(input[, base]) -For example: `'sub.host.com:8080'` +* `input` {string} The input URL to parse +* `base` {string|URL} The base URL to resolve against if the `input` is not + absolute. -### urlObject.hostname +Creates a new `URL` object by parsing the `input` relative to the `base`. If +`base` is passed as a string, it will be parsed equivalent to `new URL(base)`. -The `hostname` property is the lower-cased host name portion of the `host` -component *without* the `port` included. +```js +const myURL = new URL('/foo', 'https://example.org/'); + // https://example.org/foo +``` -For example: `'sub.host.com'` +A `TypeError` will be thrown if the `input` or `base` are not valid URLs. Note +that an effort will be made to coerce the given values into strings. For +instance: -### urlObject.href +```js +const myURL = new URL({toString: () => 'https://example.org/'}); + // https://example.org/ +``` -The `href` property is the full URL string that was parsed with both the -`protocol` and `host` components converted to lower-case. +Unicode characters appearing within the hostname of `input` will be +automatically converted to ASCII using the [Punycode][] algorithm. -For example: `'http://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash'` +```js +const myURL = new URL('https://你好你好'); + // https://xn--6qqa088eba/ +``` -### urlObject.path +Additional [examples of parsed URLs][] may be found in the WHATWG URL Standard. -The `path` property is a concatenation of the `pathname` and `search` -components. +#### url.hash -For example: `'/p/a/t/h?query=string'` +* {string} -No decoding of the `path` is performed. +Gets and sets the fragment portion of the URL. -### urlObject.pathname +```js +const myURL = new URL('https://example.org/foo#bar'); +console.log(myURL.hash); + // Prints #bar -The `pathname` property consists of the entire path section of the URL. This -is everything following the `host` (including the `port`) and before the start -of the `query` or `hash` components, delimited by either the ASCII question -mark (`?`) or hash (`#`) characters. +myURL.hash = 'baz'; +console.log(myURL.href); + // Prints https://example.org/foo#baz +``` -For example `'/p/a/t/h'` +Invalid URL characters included in the value assigned to the `hash` property +are [percent-encoded][]. Note that the selection of which characters to +percent-encode may vary somewhat from what the [`url.parse()`][] and +[`url.format()`][] methods would produce. -No decoding of the path string is performed. +#### url.host -### urlObject.port +* {string} -The `port` property is the numeric port portion of the `host` component. +Gets and sets the host portion of the URL. -For example: `'8080'` +```js +const myURL = new URL('https://example.org:81/foo'); +console.log(myURL.host); + // Prints example.org:81 -### urlObject.protocol +myURL.host = 'example.com:82'; +console.log(myURL.href); + // Prints https://example.com:82/foo +``` -The `protocol` property identifies the URL's lower-cased protocol scheme. +Invalid host values assigned to the `host` property are ignored. -For example: `'http:'` +#### url.hostname -### urlObject.query +* {string} -The `query` property is either the query string without the leading ASCII -question mark (`?`), or an object returned by the [`querystring`][] module's -`parse()` method. Whether the `query` property is a string or object is -determined by the `parseQueryString` argument passed to `url.parse()`. +Gets and sets the hostname portion of the URL. The key difference between +`url.host` and `url.hostname` is that `url.hostname` does *not* include the +port. -For example: `'query=string'` or `{'query': 'string'}` +```js +const myURL = new URL('https://example.org:81/foo'); +console.log(myURL.hostname); + // Prints example.org -If returned as a string, no decoding of the query string is performed. If -returned as an object, both keys and values are decoded. +myURL.hostname = 'example.com:82'; +console.log(myURL.href); + // Prints https://example.com:81/foo +``` + +Invalid hostname values assigned to the `hostname` property are ignored. -### urlObject.search +#### url.href -The `search` property consists of the entire "query string" portion of the -URL, including the leading ASCII question mark (`?`) character. +* {string} -For example: `'?query=string'` +Gets and sets the serialized URL. -No decoding of the query string is performed. +```js +const myURL = new URL('https://example.org/foo'); +console.log(myURL.href); + // Prints https://example.org/foo -### urlObject.slashes +myURL.href = 'https://example.com/bar'; + // Prints https://example.com/bar +``` -The `slashes` property is a `boolean` with a value of `true` if two ASCII -forward-slash characters (`/`) are required following the colon in the -`protocol`. +Getting the value of the `href` property is equivalent to calling +[`url.toString()`][]. -## url.domainToASCII(domain) - +Setting the value of this property to a new value is equivalent to creating a +new `URL` object using [`new URL(value)`][`new URL()`]. Each of the `URL` +object's properties will be modified. -> Stability: 1 - Experimental +If the value assigned to the `href` property is not a valid URL, a `TypeError` +will be thrown. -* `domain` {string} -* Returns: {string} +#### url.origin -Returns the [Punycode][] ASCII serialization of the `domain`. If `domain` is an -invalid domain, the empty string is returned. +* {string} -It performs the inverse operation to [`url.domainToUnicode()`][]. +Gets the read-only serialization of the URL's origin. Unicode characters that +may be contained within the hostname will be encoded as-is without [Punycode][] +encoding. ```js -const url = require('url'); -console.log(url.domainToASCII('español.com')); - // Prints xn--espaol-zwa.com -console.log(url.domainToASCII('中文.com')); - // Prints xn--fiq228c.com -console.log(url.domainToASCII('xn--iñvalid.com')); - // Prints an empty string +const myURL = new URL('https://example.org/foo/bar?baz'); +console.log(myURL.origin); + // Prints https://example.org ``` -## url.domainToUnicode(domain) - +```js +const idnURL = new URL('https://你好你好'); +console.log(idnURL.origin); + // Prints https://你好你好 -> Stability: 1 - Experimental +console.log(idnURL.hostname); + // Prints xn--6qqa088eba +``` -* `domain` {string} -* Returns: {string} +#### url.password -Returns the Unicode serialization of the `domain`. If `domain` is an invalid -domain, the empty string is returned. +* {string} -It performs the inverse operation to [`url.domainToASCII()`][]. +Gets and sets the password portion of the URL. ```js -const url = require('url'); -console.log(url.domainToUnicode('xn--espaol-zwa.com')); - // Prints español.com -console.log(url.domainToUnicode('xn--fiq228c.com')); - // Prints 中文.com -console.log(url.domainToUnicode('xn--iñvalid.com')); - // Prints an empty string +const myURL = new URL('https://abc:xyz@example.com'); +console.log(myURL.password); + // Prints xyz + +myURL.password = '123'; +console.log(myURL.href); + // Prints https://abc:123@example.com ``` -## url.format(urlObject) - +Invalid URL characters included in the value assigned to the `password` property +are [percent-encoded][]. Note that the selection of which characters to +percent-encode may vary somewhat from what the [`url.parse()`][] and +[`url.format()`][] methods would produce. -* `urlObject` {Object|string} A URL object (as returned by `url.parse()` or - constructed otherwise). If a string, it is converted to an object by passing - it to `url.parse()`. +#### url.pathname -The `url.format()` method returns a formatted URL string derived from -`urlObject`. +* {string} -If `urlObject` is not an object or a string, `url.parse()` will throw a -[`TypeError`][]. +Gets and sets the path portion of the URL. -The formatting process operates as follows: - -* A new empty string `result` is created. -* If `urlObject.protocol` is a string, it is appended as-is to `result`. -* Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an - [`Error`][] is thrown. -* For all string values of `urlObject.protocol` that *do not end* with an ASCII - colon (`:`) character, the literal string `:` will be appended to `result`. -* If either of the following conditions is true, then the literal string `//` - will be appended to `result`: - * `urlObject.slashes` property is true; - * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or - `file`; -* If the value of the `urlObject.auth` property is truthy, and either - `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of - `urlObject.auth` will be coerced into a string and appended to `result` - followed by the literal string `@`. -* If the `urlObject.host` property is `undefined` then: - * If the `urlObject.hostname` is a string, it is appended to `result`. - * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, - an [`Error`][] is thrown. - * If the `urlObject.port` property value is truthy, and `urlObject.hostname` - is not `undefined`: - * The literal string `:` is appended to `result`, and - * The value of `urlObject.port` is coerced to a string and appended to - `result`. -* Otherwise, if the `urlObject.host` property value is truthy, the value of - `urlObject.host` is coerced to a string and appended to `result`. -* If the `urlObject.pathname` property is a string that is not an empty string: - * If the `urlObject.pathname` *does not start* with an ASCII forward slash - (`/`), then the literal string '/' is appended to `result`. - * The value of `urlObject.pathname` is appended to `result`. -* Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an - [`Error`][] is thrown. -* If the `urlObject.search` property is `undefined` and if the `urlObject.query` - property is an `Object`, the literal string `?` is appended to `result` - followed by the output of calling the [`querystring`][] module's `stringify()` - method passing the value of `urlObject.query`. -* Otherwise, if `urlObject.search` is a string: - * If the value of `urlObject.search` *does not start* with the ASCII question - mark (`?`) character, the literal string `?` is appended to `result`. - * The value of `urlObject.search` is appended to `result`. -* Otherwise, if `urlObject.search` is not `undefined` and is not a string, an - [`Error`][] is thrown. -* If the `urlObject.hash` property is a string: - * If the value of `urlObject.hash` *does not start* with the ASCII hash (`#`) - character, the literal string `#` is appended to `result`. - * The value of `urlObject.hash` is appended to `result`. -* Otherwise, if the `urlObject.hash` property is not `undefined` and is not a - string, an [`Error`][] is thrown. -* `result` is returned. - -## url.format(URL[, options]) - - -* `URL` {URL} A [WHATWG URL][] object -* `options` {Object} - * `auth` {boolean} `true` if the serialized URL string should include the - username and password, `false` otherwise. Defaults to `true`. - * `fragment` {boolean} `true` if the serialized URL string should include the - fragment, `false` otherwise. Defaults to `true`. - * `search` {boolean} `true` if the serialized URL string should include the - search query, `false` otherwise. Defaults to `true`. - * `unicode` {boolean} `true` if Unicode characters appearing in the host - component of the URL string should be encoded directly as opposed to being - Punycode encoded. Defaults to `false`. - -Returns a customizable serialization of a URL String representation of a -[WHATWG URL][] object. - -The URL object has both a `toString()` method and `href` property that return -string serializations of the URL. These are not, however, customizable in -any way. The `url.format(URL[, options])` method allows for basic customization -of the output. - -For example: - -```js -const myURL = new URL('https://a:b@你好你好?abc#foo'); - -console.log(myURL.href); - // Prints https://a:b@xn--6qqa088eba/?abc#foo - -console.log(myURL.toString()); - // Prints https://a:b@xn--6qqa088eba/?abc#foo - -console.log(url.format(myURL, {fragment: false, unicode: true, auth: false})); - // Prints 'https://你好你好?abc' -``` - -## url.parse(urlString[, parseQueryString[, slashesDenoteHost]]) - - -* `urlString` {string} The URL string to parse. -* `parseQueryString` {boolean} If `true`, the `query` property will always - be set to an object returned by the [`querystring`][] module's `parse()` - method. If `false`, the `query` property on the returned URL object will be an - unparsed, undecoded string. Defaults to `false`. -* `slashesDenoteHost` {boolean} If `true`, the first token after the literal - string `//` and preceding the next `/` will be interpreted as the `host`. - For instance, given `//foo/bar`, the result would be - `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. - Defaults to `false`. - -The `url.parse()` method takes a URL string, parses it, and returns a URL -object. - -A `TypeError` is thrown if `urlString` is not a string. - -A `URIError` is thrown if the `auth` property is present but cannot be decoded. - -## url.resolve(from, to) - - -* `from` {string} The Base URL being resolved against. -* `to` {string} The HREF URL being resolved. - -The `url.resolve()` method resolves a target URL relative to a base URL in a -manner similar to that of a Web browser resolving an anchor tag HREF. - -For example: - -```js -url.resolve('/one/two/three', 'four'); // '/one/two/four' -url.resolve('http://example.com/', '/one'); // 'http://example.com/one' -url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' -``` - -## Escaped Characters - -URLs are only permitted to contain a certain range of characters. Spaces (`' '`) -and the following characters will be automatically escaped in the -properties of URL objects: - -```txt -< > " ` \r \n \t { } | \ ^ ' -``` - -For example, the ASCII space character (`' '`) is encoded as `%20`. The ASCII -forward slash (`/`) character is encoded as `%3C`. - -## The WHATWG URL API - - -The `url` module provides an implementation of the [WHATWG URL Standard][] as -an alternative to the existing `url.parse()` API. - -```js -const URL = require('url').URL; -const myURL = new URL('https://example.org/foo'); - -console.log(myURL.href); // https://example.org/foo -console.log(myURL.protocol); // https: -console.log(myURL.hostname); // example.org -console.log(myURL.pathname); // /foo -``` - -*Note*: Using the `delete` keyword (e.g. `delete myURL.protocol`, -`delete myURL.pathname`, etc) has no effect but will still return `true`. - -A comparison between this API and `url.parse()` is given below. Above the URL -`'http://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash'`, properties of an -object returned by `url.parse()` are shown. Below it are properties of a WHATWG -`URL` object. - -*Note*: WHATWG URL's `origin` property includes `protocol` and `host`, but not -`username` or `password`. - -```txt -┌─────────────────────────────────────────────────────────────────────────────────────────────┐ -│ href │ -├──────────┬──┬─────────────────────┬─────────────────────┬───────────────────────────┬───────┤ -│ protocol │ │ auth │ host │ path │ hash │ -│ │ │ ├──────────────┬──────┼──────────┬────────────────┤ │ -│ │ │ │ hostname │ port │ pathname │ search │ │ -│ │ │ │ │ │ ├─┬──────────────┤ │ -│ │ │ │ │ │ │ │ query │ │ -" http: // user : pass @ sub.host.com : 8080 /p/a/t/h ? query=string #hash " -│ │ │ │ │ hostname │ port │ │ │ │ -│ │ │ │ ├──────────────┴──────┤ │ │ │ -│ protocol │ │ username │ password │ host │ │ │ │ -├──────────┴──┼──────────┴──────────┼─────────────────────┤ │ │ │ -│ origin │ │ origin │ pathname │ search │ hash │ -├─────────────┴─────────────────────┴─────────────────────┴──────────┴────────────────┴───────┤ -│ href │ -└─────────────────────────────────────────────────────────────────────────────────────────────┘ -(all spaces in the "" line should be ignored -- they are purely for formatting) -``` - -### Class: URL -#### Constructor: new URL(input[, base]) - -* `input` {string} The input URL to parse -* `base` {string|URL} The base URL to resolve against if the `input` is not - absolute. - -Creates a new `URL` object by parsing the `input` relative to the `base`. If -`base` is passed as a string, it will be parsed equivalent to `new URL(base)`. - -```js -const myURL = new URL('/foo', 'https://example.org/'); - // https://example.org/foo -``` - -A `TypeError` will be thrown if the `input` or `base` are not valid URLs. Note -that an effort will be made to coerce the given values into strings. For -instance: - -```js -const myURL = new URL({toString: () => 'https://example.org/'}); - // https://example.org/ -``` - -Unicode characters appearing within the hostname of `input` will be -automatically converted to ASCII using the [Punycode][] algorithm. - -```js -const myURL = new URL('https://你好你好'); - // https://xn--6qqa088eba/ -``` - -Additional [examples of parsed URLs][] may be found in the WHATWG URL Standard. - -#### url.hash - -* {string} - -Gets and sets the fragment portion of the URL. - -```js -const myURL = new URL('https://example.org/foo#bar'); -console.log(myURL.hash); - // Prints #bar - -myURL.hash = 'baz'; -console.log(myURL.href); - // Prints https://example.org/foo#baz -``` - -Invalid URL characters included in the value assigned to the `hash` property -are [percent-encoded][]. Note that the selection of which characters to -percent-encode may vary somewhat from what the [`url.parse()`][] and -[`url.format()`][] methods would produce. - -#### url.host - -* {string} - -Gets and sets the host portion of the URL. - -```js -const myURL = new URL('https://example.org:81/foo'); -console.log(myURL.host); - // Prints example.org:81 - -myURL.host = 'example.com:82'; -console.log(myURL.href); - // Prints https://example.com:82/foo -``` - -Invalid host values assigned to the `host` property are ignored. - -#### url.hostname - -* {string} - -Gets and sets the hostname portion of the URL. The key difference between -`url.host` and `url.hostname` is that `url.hostname` does *not* include the -port. - -```js -const myURL = new URL('https://example.org:81/foo'); -console.log(myURL.hostname); - // Prints example.org - -myURL.hostname = 'example.com:82'; -console.log(myURL.href); - // Prints https://example.com:81/foo -``` - -Invalid hostname values assigned to the `hostname` property are ignored. - -#### url.href - -* {string} - -Gets and sets the serialized URL. - -```js -const myURL = new URL('https://example.org/foo'); -console.log(myURL.href); - // Prints https://example.org/foo - -myURL.href = 'https://example.com/bar'; - // Prints https://example.com/bar -``` - -Getting the value of the `href` property is equivalent to calling -[`url.toString()`][]. - -Setting the value of this property to a new value is equivalent to creating a -new `URL` object using [`new URL(value)`][`new URL()`]. Each of the `URL` -object's properties will be modified. - -If the value assigned to the `href` property is not a valid URL, a `TypeError` -will be thrown. - -#### url.origin - -* {string} - -Gets the read-only serialization of the URL's origin. Unicode characters that -may be contained within the hostname will be encoded as-is without [Punycode][] -encoding. - -```js -const myURL = new URL('https://example.org/foo/bar?baz'); -console.log(myURL.origin); - // Prints https://example.org -``` - -```js -const idnURL = new URL('https://你好你好'); -console.log(idnURL.origin); - // Prints https://你好你好 - -console.log(idnURL.hostname); - // Prints xn--6qqa088eba -``` - -#### url.password - -* {string} - -Gets and sets the password portion of the URL. - -```js -const myURL = new URL('https://abc:xyz@example.com'); -console.log(myURL.password); - // Prints xyz - -myURL.password = '123'; -console.log(myURL.href); - // Prints https://abc:123@example.com -``` - -Invalid URL characters included in the value assigned to the `password` property -are [percent-encoded][]. Note that the selection of which characters to -percent-encode may vary somewhat from what the [`url.parse()`][] and -[`url.format()`][] methods would produce. - -#### url.pathname - -* {string} - -Gets and sets the path portion of the URL. - -```js -const myURL = new URL('https://example.org/abc/xyz?123'); -console.log(myURL.pathname); - // Prints /abc/xyz +```js +const myURL = new URL('https://example.org/abc/xyz?123'); +console.log(myURL.pathname); + // Prints /abc/xyz myURL.pathname = '/abcdef'; console.log(myURL.href); @@ -725,348 +401,675 @@ to customize the serialization process of the URL. For more flexibility, #### url.toJSON() -* Returns: {string} +* Returns: {string} + +The `toJSON()` method on the `URL` object returns the serialized URL. The +value returned is equivalent to that of [`url.href`][] and +[`url.toString()`][]. + +This method is automatically called when an `URL` object is serialized +with [`JSON.stringify()`][]. + +```js +const myURLs = [ + new URL('https://www.example.com'), + new URL('https://test.example.org') +]; +console.log(JSON.stringify(myURLs)); + // Prints ["https://www.example.com/","https://test.example.org/"] +``` + +### Class: URLSearchParams + + +The `URLSearchParams` API provides read and write access to the query of a +`URL`. The `URLSearchParams` class can also be used standalone with one of the +four following constructors. + +The WHATWG `URLSearchParams` interface and the [`querystring`][] module have +similar purpose, but the purpose of the [`querystring`][] module is more +general, as it allows the customization of delimiter characters (`&` and `=`). +On the other hand, this API is designed purely for URL query strings. + +```js +const { URL, URLSearchParams } = require('url'); + +const myURL = new URL('https://example.org/?abc=123'); +console.log(myURL.searchParams.get('abc')); + // Prints 123 + +myURL.searchParams.append('abc', 'xyz'); +console.log(myURL.href); + // Prints https://example.org/?abc=123&abc=xyz + +myURL.searchParams.delete('abc'); +myURL.searchParams.set('a', 'b'); +console.log(myURL.href); + // Prints https://example.org/?a=b + +const newSearchParams = new URLSearchParams(myURL.searchParams); +// The above is equivalent to +// const newSearchParams = new URLSearchParams(myURL.search); + +newSearchParams.append('a', 'c'); +console.log(myURL.href); + // Prints https://example.org/?a=b +console.log(newSearchParams.toString()); + // Prints a=b&a=c + +// newSearchParams.toString() is implicitly called +myURL.search = newSearchParams; +console.log(myURL.href); + // Prints https://example.org/?a=b&a=c +newSearchParams.delete('a'); +console.log(myURL.href); + // Prints https://example.org/?a=b&a=c +``` + +#### Constructor: new URLSearchParams() + +Instantiate a new empty `URLSearchParams` object. + +#### Constructor: new URLSearchParams(string) + +* `string` {string} A query string + +Parse the `string` as a query string, and use it to instantiate a new +`URLSearchParams` object. A leading `'?'`, if present, is ignored. + +```js +const { URLSearchParams } = require('url'); +let params; + +params = new URLSearchParams('user=abc&query=xyz'); +console.log(params.get('user')); + // Prints 'abc' +console.log(params.toString()); + // Prints 'user=abc&query=xyz' + +params = new URLSearchParams('?user=abc&query=xyz'); +console.log(params.toString()); + // Prints 'user=abc&query=xyz' +``` + +#### Constructor: new URLSearchParams(obj) + + +* `obj` {Object} An object representing a collection of key-value pairs + +Instantiate a new `URLSearchParams` object with a query hash map. The key and +value of each property of `obj` are always coerced to strings. + +*Note*: Unlike [`querystring`][] module, duplicate keys in the form of array +values are not allowed. Arrays are stringified using [`array.toString()`][], +which simply joins all array elements with commas. + +```js +const { URLSearchParams } = require('url'); +const params = new URLSearchParams({ + user: 'abc', + query: ['first', 'second'] +}); +console.log(params.getAll('query')); + // Prints ['first,second'] +console.log(params.toString()); + // Prints 'user=abc&query=first%2Csecond' +``` + +#### Constructor: new URLSearchParams(iterable) + + +* `iterable` {Iterable} An iterable object whose elements are key-value pairs + +Instantiate a new `URLSearchParams` object with an iterable map in a way that +is similar to [`Map`][]'s constructor. `iterable` can be an Array or any +iterable object. That means `iterable` can be another `URLSearchParams`, in +which case the constructor will simply create a clone of the provided +`URLSearchParams`. Elements of `iterable` are key-value pairs, and can +themselves be any iterable object. + +Duplicate keys are allowed. + +```js +const { URLSearchParams } = require('url'); +let params; + +// Using an array +params = new URLSearchParams([ + ['user', 'abc'], + ['query', 'first'], + ['query', 'second'] +]); +console.log(params.toString()); + // Prints 'user=abc&query=first&query=second' + +// Using a Map object +const map = new Map(); +map.set('user', 'abc'); +map.set('query', 'xyz'); +params = new URLSearchParams(map); +console.log(params.toString()); + // Prints 'user=abc&query=xyz' + +// Using a generator function +function* getQueryPairs() { + yield ['user', 'abc']; + yield ['query', 'first']; + yield ['query', 'second']; +} +params = new URLSearchParams(getQueryPairs()); +console.log(params.toString()); + // Prints 'user=abc&query=first&query=second' + +// Each key-value pair must have exactly two elements +new URLSearchParams([ + ['user', 'abc', 'error'] +]); + // Throws TypeError: Each query pair must be a name/value tuple +``` + +#### urlSearchParams.append(name, value) + +* `name` {string} +* `value` {string} + +Append a new name-value pair to the query string. + +#### urlSearchParams.delete(name) + +* `name` {string} + +Remove all name-value pairs whose name is `name`. + +#### urlSearchParams.entries() + +* Returns: {Iterator} + +Returns an ES6 Iterator over each of the name-value pairs in the query. +Each item of the iterator is a JavaScript Array. The first item of the Array +is the `name`, the second item of the Array is the `value`. + +Alias for [`urlSearchParams[@@iterator]()`][`urlSearchParams@@iterator()`]. + +#### urlSearchParams.forEach(fn[, thisArg]) + +* `fn` {Function} Function invoked for each name-value pair in the query. +* `thisArg` {Object} Object to be used as `this` value for when `fn` is called + +Iterates over each name-value pair in the query and invokes the given function. + +```js +const URL = require('url').URL; +const myURL = new URL('https://example.org/?a=b&c=d'); +myURL.searchParams.forEach((value, name, searchParams) => { + console.log(name, value, myURL.searchParams === searchParams); +}); + // Prints: + // a b true + // c d true +``` + +#### urlSearchParams.get(name) + +* `name` {string} +* Returns: {string} or `null` if there is no name-value pair with the given + `name`. + +Returns the value of the first name-value pair whose name is `name`. If there +are no such pairs, `null` is returned. + +#### urlSearchParams.getAll(name) + +* `name` {string} +* Returns: {Array} + +Returns the values of all name-value pairs whose name is `name`. If there are +no such pairs, an empty array is returned. + +#### urlSearchParams.has(name) + +* `name` {string} +* Returns: {boolean} + +Returns `true` if there is at least one name-value pair whose name is `name`. + +#### urlSearchParams.keys() + +* Returns: {Iterator} + +Returns an ES6 Iterator over the names of each name-value pair. + +```js +const { URLSearchParams } = require('url'); +const params = new URLSearchParams('foo=bar&foo=baz'); +for (const name of params.keys()) { + console.log(name); +} + // Prints: + // foo + // foo +``` + +#### urlSearchParams.set(name, value) -The `toJSON()` method on the `URL` object returns the serialized URL. The -value returned is equivalent to that of [`url.href`][] and -[`url.toString()`][]. +* `name` {string} +* `value` {string} -This method is automatically called when an `URL` object is serialized -with [`JSON.stringify()`][]. +Sets the value in the `URLSearchParams` object associated with `name` to +`value`. If there are any pre-existing name-value pairs whose names are `name`, +set the first such pair's value to `value` and remove all others. If not, +append the name-value pair to the query string. ```js -const myURLs = [ - new URL('https://www.example.com'), - new URL('https://test.example.org') -]; -console.log(JSON.stringify(myURLs)); - // Prints ["https://www.example.com/","https://test.example.org/"] +const { URLSearchParams } = require('url'); + +const params = new URLSearchParams(); +params.append('foo', 'bar'); +params.append('foo', 'baz'); +params.append('abc', 'def'); +console.log(params.toString()); + // Prints foo=bar&foo=baz&abc=def + +params.set('foo', 'def'); +params.set('xyz', 'opq'); +console.log(params.toString()); + // Prints foo=def&abc=def&xyz=opq ``` -### Class: URLSearchParams +#### urlSearchParams.sort() -The `URLSearchParams` API provides read and write access to the query of a -`URL`. The `URLSearchParams` class can also be used standalone with one of the -four following constructors. +Sort all existing name-value pairs in-place by their names. Sorting is done +with a [stable sorting algorithm][], so relative order between name-value pairs +with the same name is preserved. -The WHATWG `URLSearchParams` interface and the [`querystring`][] module have -similar purpose, but the purpose of the [`querystring`][] module is more -general, as it allows the customization of delimiter characters (`&` and `=`). -On the other hand, this API is designed purely for URL query strings. +This method can be used, in particular, to increase cache hits. ```js -const { URL, URLSearchParams } = require('url'); - -const myURL = new URL('https://example.org/?abc=123'); -console.log(myURL.searchParams.get('abc')); - // Prints 123 +const params = new URLSearchParams('query[]=abc&type=search&query[]=123'); +params.sort(); +console.log(params.toString()); + // Prints query%5B%5D=abc&query%5B%5D=123&type=search +``` -myURL.searchParams.append('abc', 'xyz'); -console.log(myURL.href); - // Prints https://example.org/?abc=123&abc=xyz +#### urlSearchParams.toString() -myURL.searchParams.delete('abc'); -myURL.searchParams.set('a', 'b'); -console.log(myURL.href); - // Prints https://example.org/?a=b +* Returns: {string} -const newSearchParams = new URLSearchParams(myURL.searchParams); -// The above is equivalent to -// const newSearchParams = new URLSearchParams(myURL.search); +Returns the search parameters serialized as a string, with characters +percent-encoded where necessary. -newSearchParams.append('a', 'c'); -console.log(myURL.href); - // Prints https://example.org/?a=b -console.log(newSearchParams.toString()); - // Prints a=b&a=c +#### urlSearchParams.values() -// newSearchParams.toString() is implicitly called -myURL.search = newSearchParams; -console.log(myURL.href); - // Prints https://example.org/?a=b&a=c -newSearchParams.delete('a'); -console.log(myURL.href); - // Prints https://example.org/?a=b&a=c -``` +* Returns: {Iterator} -#### Constructor: new URLSearchParams() +Returns an ES6 Iterator over the values of each name-value pair. -Instantiate a new empty `URLSearchParams` object. +#### urlSearchParams\[@@iterator\]() -#### Constructor: new URLSearchParams(string) +* Returns: {Iterator} -* `string` {string} A query string +Returns an ES6 Iterator over each of the name-value pairs in the query string. +Each item of the iterator is a JavaScript Array. The first item of the Array +is the `name`, the second item of the Array is the `value`. -Parse the `string` as a query string, and use it to instantiate a new -`URLSearchParams` object. A leading `'?'`, if present, is ignored. +Alias for [`urlSearchParams.entries()`][]. ```js const { URLSearchParams } = require('url'); -let params; +const params = new URLSearchParams('foo=bar&xyz=baz'); +for (const [name, value] of params) { + console.log(name, value); +} + // Prints: + // foo bar + // xyz baz +``` -params = new URLSearchParams('user=abc&query=xyz'); -console.log(params.get('user')); - // Prints 'abc' -console.log(params.toString()); - // Prints 'user=abc&query=xyz' +### url.domainToASCII(domain) + -params = new URLSearchParams('?user=abc&query=xyz'); -console.log(params.toString()); - // Prints 'user=abc&query=xyz' +* `domain` {string} +* Returns: {string} + +Returns the [Punycode][] ASCII serialization of the `domain`. If `domain` is an +invalid domain, the empty string is returned. + +It performs the inverse operation to [`url.domainToUnicode()`][]. + +```js +const url = require('url'); +console.log(url.domainToASCII('español.com')); + // Prints xn--espaol-zwa.com +console.log(url.domainToASCII('中文.com')); + // Prints xn--fiq228c.com +console.log(url.domainToASCII('xn--iñvalid.com')); + // Prints an empty string ``` -#### Constructor: new URLSearchParams(obj) +### url.domainToUnicode(domain) -* `obj` {Object} An object representing a collection of key-value pairs +* `domain` {string} +* Returns: {string} -Instantiate a new `URLSearchParams` object with a query hash map. The key and -value of each property of `obj` are always coerced to strings. +Returns the Unicode serialization of the `domain`. If `domain` is an invalid +domain, the empty string is returned. -*Note*: Unlike [`querystring`][] module, duplicate keys in the form of array -values are not allowed. Arrays are stringified using [`array.toString()`][], -which simply joins all array elements with commas. +It performs the inverse operation to [`url.domainToASCII()`][]. ```js -const { URLSearchParams } = require('url'); -const params = new URLSearchParams({ - user: 'abc', - query: ['first', 'second'] -}); -console.log(params.getAll('query')); - // Prints ['first,second'] -console.log(params.toString()); - // Prints 'user=abc&query=first%2Csecond' +const url = require('url'); +console.log(url.domainToUnicode('xn--espaol-zwa.com')); + // Prints español.com +console.log(url.domainToUnicode('xn--fiq228c.com')); + // Prints 中文.com +console.log(url.domainToUnicode('xn--iñvalid.com')); + // Prints an empty string ``` -#### Constructor: new URLSearchParams(iterable) +### url.format(URL[, options]) -* `iterable` {Iterable} An iterable object whose elements are key-value pairs +* `URL` {URL} A [WHATWG URL][] object +* `options` {Object} + * `auth` {boolean} `true` if the serialized URL string should include the + username and password, `false` otherwise. Defaults to `true`. + * `fragment` {boolean} `true` if the serialized URL string should include the + fragment, `false` otherwise. Defaults to `true`. + * `search` {boolean} `true` if the serialized URL string should include the + search query, `false` otherwise. Defaults to `true`. + * `unicode` {boolean} `true` if Unicode characters appearing in the host + component of the URL string should be encoded directly as opposed to being + Punycode encoded. Defaults to `false`. -Instantiate a new `URLSearchParams` object with an iterable map in a way that -is similar to [`Map`][]'s constructor. `iterable` can be an Array or any -iterable object. That means `iterable` can be another `URLSearchParams`, in -which case the constructor will simply create a clone of the provided -`URLSearchParams`. Elements of `iterable` are key-value pairs, and can -themselves be any iterable object. +Returns a customizable serialization of a URL String representation of a +[WHATWG URL][] object. -Duplicate keys are allowed. +The URL object has both a `toString()` method and `href` property that return +string serializations of the URL. These are not, however, customizable in +any way. The `url.format(URL[, options])` method allows for basic customization +of the output. -```js -const { URLSearchParams } = require('url'); -let params; +For example: -// Using an array -params = new URLSearchParams([ - ['user', 'abc'], - ['query', 'first'], - ['query', 'second'] -]); -console.log(params.toString()); - // Prints 'user=abc&query=first&query=second' +```js +const myURL = new URL('https://a:b@你好你好?abc#foo'); -// Using a Map object -const map = new Map(); -map.set('user', 'abc'); -map.set('query', 'xyz'); -params = new URLSearchParams(map); -console.log(params.toString()); - // Prints 'user=abc&query=xyz' +console.log(myURL.href); + // Prints https://a:b@xn--6qqa088eba/?abc#foo -// Using a generator function -function* getQueryPairs() { - yield ['user', 'abc']; - yield ['query', 'first']; - yield ['query', 'second']; -} -params = new URLSearchParams(getQueryPairs()); -console.log(params.toString()); - // Prints 'user=abc&query=first&query=second' +console.log(myURL.toString()); + // Prints https://a:b@xn--6qqa088eba/?abc#foo -// Each key-value pair must have exactly two elements -new URLSearchParams([ - ['user', 'abc', 'error'] -]); - // Throws TypeError: Each query pair must be a name/value tuple +console.log(url.format(myURL, {fragment: false, unicode: true, auth: false})); + // Prints 'https://你好你好?abc' ``` -#### urlSearchParams.append(name, value) +## Legacy URL API + +### Legacy urlObject + +The legacy urlObject (`require('url').Url`) is created and returned by the +`url.parse()` function. + +#### urlObject.auth + +The `auth` property is the username and password portion of the URL, also +referred to as "userinfo". This string subset follows the `protocol` and +double slashes (if present) and precedes the `host` component, delimited by an +ASCII "at sign" (`@`). The format of the string is `{username}[:{password}]`, +with the `[:{password}]` portion being optional. + +For example: `'user:pass'` + +#### urlObject.hash + +The `hash` property consists of the "fragment" portion of the URL including +the leading ASCII hash (`#`) character. + +For example: `'#hash'` + +#### urlObject.host -* `name` {string} -* `value` {string} +The `host` property is the full lower-cased host portion of the URL, including +the `port` if specified. -Append a new name-value pair to the query string. +For example: `'sub.host.com:8080'` -#### urlSearchParams.delete(name) +#### urlObject.hostname -* `name` {string} +The `hostname` property is the lower-cased host name portion of the `host` +component *without* the `port` included. -Remove all name-value pairs whose name is `name`. +For example: `'sub.host.com'` -#### urlSearchParams.entries() +#### urlObject.href -* Returns: {Iterator} +The `href` property is the full URL string that was parsed with both the +`protocol` and `host` components converted to lower-case. -Returns an ES6 Iterator over each of the name-value pairs in the query. -Each item of the iterator is a JavaScript Array. The first item of the Array -is the `name`, the second item of the Array is the `value`. +For example: `'http://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash'` -Alias for [`urlSearchParams[@@iterator]()`][`urlSearchParams@@iterator()`]. +#### urlObject.path -#### urlSearchParams.forEach(fn[, thisArg]) +The `path` property is a concatenation of the `pathname` and `search` +components. -* `fn` {Function} Function invoked for each name-value pair in the query. -* `thisArg` {Object} Object to be used as `this` value for when `fn` is called +For example: `'/p/a/t/h?query=string'` -Iterates over each name-value pair in the query and invokes the given function. +No decoding of the `path` is performed. -```js -const URL = require('url').URL; -const myURL = new URL('https://example.org/?a=b&c=d'); -myURL.searchParams.forEach((value, name, searchParams) => { - console.log(name, value, myURL.searchParams === searchParams); -}); - // Prints: - // a b true - // c d true -``` +#### urlObject.pathname -#### urlSearchParams.get(name) +The `pathname` property consists of the entire path section of the URL. This +is everything following the `host` (including the `port`) and before the start +of the `query` or `hash` components, delimited by either the ASCII question +mark (`?`) or hash (`#`) characters. -* `name` {string} -* Returns: {string} or `null` if there is no name-value pair with the given - `name`. +For example `'/p/a/t/h'` -Returns the value of the first name-value pair whose name is `name`. If there -are no such pairs, `null` is returned. +No decoding of the path string is performed. -#### urlSearchParams.getAll(name) +#### urlObject.port -* `name` {string} -* Returns: {Array} +The `port` property is the numeric port portion of the `host` component. -Returns the values of all name-value pairs whose name is `name`. If there are -no such pairs, an empty array is returned. +For example: `'8080'` -#### urlSearchParams.has(name) +#### urlObject.protocol -* `name` {string} -* Returns: {boolean} +The `protocol` property identifies the URL's lower-cased protocol scheme. -Returns `true` if there is at least one name-value pair whose name is `name`. +For example: `'http:'` -#### urlSearchParams.keys() +#### urlObject.query -* Returns: {Iterator} +The `query` property is either the query string without the leading ASCII +question mark (`?`), or an object returned by the [`querystring`][] module's +`parse()` method. Whether the `query` property is a string or object is +determined by the `parseQueryString` argument passed to `url.parse()`. -Returns an ES6 Iterator over the names of each name-value pair. +For example: `'query=string'` or `{'query': 'string'}` -```js -const { URLSearchParams } = require('url'); -const params = new URLSearchParams('foo=bar&foo=baz'); -for (const name of params.keys()) { - console.log(name); -} - // Prints: - // foo - // foo -``` +If returned as a string, no decoding of the query string is performed. If +returned as an object, both keys and values are decoded. -#### urlSearchParams.set(name, value) +#### urlObject.search -* `name` {string} -* `value` {string} +The `search` property consists of the entire "query string" portion of the +URL, including the leading ASCII question mark (`?`) character. -Sets the value in the `URLSearchParams` object associated with `name` to -`value`. If there are any pre-existing name-value pairs whose names are `name`, -set the first such pair's value to `value` and remove all others. If not, -append the name-value pair to the query string. +For example: `'?query=string'` -```js -const { URLSearchParams } = require('url'); +No decoding of the query string is performed. -const params = new URLSearchParams(); -params.append('foo', 'bar'); -params.append('foo', 'baz'); -params.append('abc', 'def'); -console.log(params.toString()); - // Prints foo=bar&foo=baz&abc=def +#### urlObject.slashes -params.set('foo', 'def'); -params.set('xyz', 'opq'); -console.log(params.toString()); - // Prints foo=def&abc=def&xyz=opq -``` +The `slashes` property is a `boolean` with a value of `true` if two ASCII +forward-slash characters (`/`) are required following the colon in the +`protocol`. -#### urlSearchParams.sort() +### url.format(urlObject) -Sort all existing name-value pairs in-place by their names. Sorting is done -with a [stable sorting algorithm][], so relative order between name-value pairs -with the same name is preserved. +* `urlObject` {Object|string} A URL object (as returned by `url.parse()` or + constructed otherwise). If a string, it is converted to an object by passing + it to `url.parse()`. -This method can be used, in particular, to increase cache hits. +The `url.format()` method returns a formatted URL string derived from +`urlObject`. -```js -const params = new URLSearchParams('query[]=abc&type=search&query[]=123'); -params.sort(); -console.log(params.toString()); - // Prints query%5B%5D=abc&query%5B%5D=123&type=search -``` +If `urlObject` is not an object or a string, `url.parse()` will throw a +[`TypeError`][]. -#### urlSearchParams.toString() +The formatting process operates as follows: -* Returns: {string} +* A new empty string `result` is created. +* If `urlObject.protocol` is a string, it is appended as-is to `result`. +* Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an + [`Error`][] is thrown. +* For all string values of `urlObject.protocol` that *do not end* with an ASCII + colon (`:`) character, the literal string `:` will be appended to `result`. +* If either of the following conditions is true, then the literal string `//` + will be appended to `result`: + * `urlObject.slashes` property is true; + * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or + `file`; +* If the value of the `urlObject.auth` property is truthy, and either + `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of + `urlObject.auth` will be coerced into a string and appended to `result` + followed by the literal string `@`. +* If the `urlObject.host` property is `undefined` then: + * If the `urlObject.hostname` is a string, it is appended to `result`. + * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + an [`Error`][] is thrown. + * If the `urlObject.port` property value is truthy, and `urlObject.hostname` + is not `undefined`: + * The literal string `:` is appended to `result`, and + * The value of `urlObject.port` is coerced to a string and appended to + `result`. +* Otherwise, if the `urlObject.host` property value is truthy, the value of + `urlObject.host` is coerced to a string and appended to `result`. +* If the `urlObject.pathname` property is a string that is not an empty string: + * If the `urlObject.pathname` *does not start* with an ASCII forward slash + (`/`), then the literal string '/' is appended to `result`. + * The value of `urlObject.pathname` is appended to `result`. +* Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an + [`Error`][] is thrown. +* If the `urlObject.search` property is `undefined` and if the `urlObject.query` + property is an `Object`, the literal string `?` is appended to `result` + followed by the output of calling the [`querystring`][] module's `stringify()` + method passing the value of `urlObject.query`. +* Otherwise, if `urlObject.search` is a string: + * If the value of `urlObject.search` *does not start* with the ASCII question + mark (`?`) character, the literal string `?` is appended to `result`. + * The value of `urlObject.search` is appended to `result`. +* Otherwise, if `urlObject.search` is not `undefined` and is not a string, an + [`Error`][] is thrown. +* If the `urlObject.hash` property is a string: + * If the value of `urlObject.hash` *does not start* with the ASCII hash (`#`) + character, the literal string `#` is appended to `result`. + * The value of `urlObject.hash` is appended to `result`. +* Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + string, an [`Error`][] is thrown. +* `result` is returned. -Returns the search parameters serialized as a string, with characters -percent-encoded where necessary. -#### urlSearchParams.values() +### url.parse(urlString[, parseQueryString[, slashesDenoteHost]]) + -* Returns: {Iterator} +* `urlString` {string} The URL string to parse. +* `parseQueryString` {boolean} If `true`, the `query` property will always + be set to an object returned by the [`querystring`][] module's `parse()` + method. If `false`, the `query` property on the returned URL object will be an + unparsed, undecoded string. Defaults to `false`. +* `slashesDenoteHost` {boolean} If `true`, the first token after the literal + string `//` and preceding the next `/` will be interpreted as the `host`. + For instance, given `//foo/bar`, the result would be + `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. + Defaults to `false`. -Returns an ES6 Iterator over the values of each name-value pair. +The `url.parse()` method takes a URL string, parses it, and returns a URL +object. -#### urlSearchParams\[@@iterator\]() +A `TypeError` is thrown if `urlString` is not a string. -* Returns: {Iterator} +A `URIError` is thrown if the `auth` property is present but cannot be decoded. -Returns an ES6 Iterator over each of the name-value pairs in the query string. -Each item of the iterator is a JavaScript Array. The first item of the Array -is the `name`, the second item of the Array is the `value`. +### url.resolve(from, to) + -Alias for [`urlSearchParams.entries()`][]. +* `from` {string} The Base URL being resolved against. +* `to` {string} The HREF URL being resolved. + +The `url.resolve()` method resolves a target URL relative to a base URL in a +manner similar to that of a Web browser resolving an anchor tag HREF. + +For example: ```js -const { URLSearchParams } = require('url'); -const params = new URLSearchParams('foo=bar&xyz=baz'); -for (const [name, value] of params) { - console.log(name, value); -} - // Prints: - // foo bar - // xyz baz +url.resolve('/one/two/three', 'four'); // '/one/two/four' +url.resolve('http://example.com/', '/one'); // 'http://example.com/one' +url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' ``` -### Percent-Encoding in the WHATWG URL Standard +## Percent-Encoding in URLs URLs are permitted to only contain a certain range of characters. Any character falling outside of that range must be encoded. How such characters are encoded, and which characters to encode depends entirely on where the character is -located within the structure of the URL. The WHATWG URL Standard uses a more -selective and fine grained approach to selecting encoded characters than that -used by the older [`url.parse()`][] and [`url.format()`][] methods. +located within the structure of the URL. + +### Legacy API + +Within the Legacy API, spaces (`' '`) and the following characters will be +automatically escaped in the properties of URL objects: + +```txt +< > " ` \r \n \t { } | \ ^ ' +``` + +For example, the ASCII space character (`' '`) is encoded as `%20`. The ASCII +forward slash (`/`) character is encoded as `%3C`. + +### WHATWG API + +The [WHATWG URL Standard][] uses a more selective and fine grained approach to +selecting encoded characters than that used by the Legacy API. The WHATWG algorithm defines three "percent-encode sets" that describe ranges of characters that must be percent-encoded: @@ -1101,7 +1104,6 @@ console.log(myURL.origin); // Prints https://π.com ``` - [`Error`]: errors.html#errors_class_error [`JSON.stringify()`]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify [`Map`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map