{ "type": "module", "source": "doc/api/url.md", "modules": [ { "textRaw": "URL", "name": "url", "introduced_in": "v0.10.0", "stability": 2, "stabilityText": "Stable", "desc": "
Source Code: lib/url.js
\nThe url
module provides utilities for URL resolution and parsing. It can be\naccessed using:
const url = require('url');\n
",
"modules": [
{
"textRaw": "URL strings and URL objects",
"name": "url_strings_and_url_objects",
"desc": "A URL string is a structured string containing multiple meaningful components.\nWhen parsed, a URL object is returned containing properties for each of these\ncomponents.
\nThe url
module provides two APIs for working with URLs: a legacy API that is\nNode.js specific, and a newer API that implements the same\nWHATWG URL Standard used by web browsers.
A comparison between the WHATWG and Legacy APIs is provided below. Above the URL\n'https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'
, properties\nof an object returned by the legacy url.parse()
are shown. Below it are\nproperties of a WHATWG URL
object.
WHATWG URL's origin
property includes protocol
and host
, but not\nusername
or password
.
┌────────────────────────────────────────────────────────────────────────────────────────────────┐\n│ href │\n├──────────┬──┬─────────────────────┬────────────────────────┬───────────────────────────┬───────┤\n│ protocol │ │ auth │ host │ path │ hash │\n│ │ │ ├─────────────────┬──────┼──────────┬────────────────┤ │\n│ │ │ │ hostname │ port │ pathname │ search │ │\n│ │ │ │ │ │ ├─┬──────────────┤ │\n│ │ │ │ │ │ │ │ query │ │\n\" https: // user : pass @ sub.example.com : 8080 /p/a/t/h ? query=string #hash \"\n│ │ │ │ │ hostname │ port │ │ │ │\n│ │ │ │ ├─────────────────┴──────┤ │ │ │\n│ protocol │ │ username │ password │ host │ │ │ │\n├──────────┴──┼──────────┴──────────┼────────────────────────┤ │ │ │\n│ origin │ │ origin │ pathname │ search │ hash │\n├─────────────┴─────────────────────┴────────────────────────┴──────────┴────────────────┴───────┤\n│ href │\n└────────────────────────────────────────────────────────────────────────────────────────────────┘\n(All spaces in the \"\" line should be ignored. They are purely for formatting.)\n
\nParsing the URL string using the WHATWG API:
\nconst myURL =\n new URL('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');\n
\nParsing the URL string using the Legacy API:
\nconst url = require('url');\nconst myURL =\n url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');\n
",
"modules": [
{
"textRaw": "Constructing a URL from component parts and getting the constructed string",
"name": "constructing_a_url_from_component_parts_and_getting_the_constructed_string",
"desc": "It is possible to construct a WHATWG URL from component parts using either the\nproperty setters or a template literal string:
\nconst myURL = new URL('https://example.org');\nmyURL.pathname = '/a/b/c';\nmyURL.search = '?d=e';\nmyURL.hash = '#fgh';\n
\nconst pathname = '/a/b/c';\nconst search = '?d=e';\nconst hash = '#fgh';\nconst myURL = new URL(`https://example.org${pathname}${search}${hash}`);\n
\nTo get the constructed URL string, use the href
property accessor:
console.log(myURL.href);\n
",
"type": "module",
"displayName": "Constructing a URL from component parts and getting the constructed string"
}
],
"type": "module",
"displayName": "URL strings and URL objects"
},
{
"textRaw": "The WHATWG URL API",
"name": "the_whatwg_url_api",
"classes": [
{
"textRaw": "Class: `URL`",
"type": "class",
"name": "URL",
"meta": {
"added": [
"v7.0.0",
"v6.13.0"
],
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18281",
"description": "The class is now available on the global object."
}
]
},
"desc": "Browser-compatible URL
class, implemented by following the WHATWG URL\nStandard. Examples of parsed URLs may be found in the Standard itself.\nThe URL
class is also available on the global object.
In accordance with browser conventions, all properties of URL
objects\nare implemented as getters and setters on the class prototype, rather than as\ndata properties on the object itself. Thus, unlike legacy urlObject
s,\nusing the delete
keyword on any properties of URL
objects (e.g. delete myURL.protocol
, delete myURL.pathname
, etc) has no effect but will still\nreturn true
.
Gets and sets the fragment portion of the URL.
\nconst myURL = new URL('https://example.org/foo#bar');\nconsole.log(myURL.hash);\n// Prints #bar\n\nmyURL.hash = 'baz';\nconsole.log(myURL.href);\n// Prints https://example.org/foo#baz\n
\nInvalid URL characters included in the value assigned to the hash
property\nare percent-encoded. The selection of which characters to\npercent-encode may vary somewhat from what the url.parse()
and\nurl.format()
methods would produce.
Gets and sets the host portion of the URL.
\nconst myURL = new URL('https://example.org:81/foo');\nconsole.log(myURL.host);\n// Prints example.org:81\n\nmyURL.host = 'example.com:82';\nconsole.log(myURL.href);\n// Prints https://example.com:82/foo\n
\nInvalid host values assigned to the host
property are ignored.
Gets and sets the host name portion of the URL. The key difference between\nurl.host
and url.hostname
is that url.hostname
does not include the\nport.
const myURL = new URL('https://example.org:81/foo');\nconsole.log(myURL.hostname);\n// Prints example.org\n\n// Setting the hostname does not change the port\nmyURL.hostname = 'example.com:82';\nconsole.log(myURL.href);\n// Prints https://example.com:81/foo\n\n// Use myURL.host to change the hostname and port\nmyURL.host = 'example.org:82';\nconsole.log(myURL.href);\n// Prints https://example.org:82/foo\n
\nInvalid host name values assigned to the hostname
property are ignored.
Gets and sets the serialized URL.
\nconst myURL = new URL('https://example.org/foo');\nconsole.log(myURL.href);\n// Prints https://example.org/foo\n\nmyURL.href = 'https://example.com/bar';\nconsole.log(myURL.href);\n// Prints https://example.com/bar\n
\nGetting the value of the href
property is equivalent to calling\nurl.toString()
.
Setting the value of this property to a new value is equivalent to creating a\nnew URL
object using new URL(value)
. Each of the URL
\nobject's properties will be modified.
If the value assigned to the href
property is not a valid URL, a TypeError
\nwill be thrown.
Gets the read-only serialization of the URL's origin.
\nconst myURL = new URL('https://example.org/foo/bar?baz');\nconsole.log(myURL.origin);\n// Prints https://example.org\n
\nconst idnURL = new URL('https://測試');\nconsole.log(idnURL.origin);\n// Prints https://xn--g6w251d\n\nconsole.log(idnURL.hostname);\n// Prints xn--g6w251d\n
"
},
{
"textRaw": "`password` {string}",
"type": "string",
"name": "password",
"desc": "Gets and sets the password portion of the URL.
\nconst myURL = new URL('https://abc:xyz@example.com');\nconsole.log(myURL.password);\n// Prints xyz\n\nmyURL.password = '123';\nconsole.log(myURL.href);\n// Prints https://abc:123@example.com\n
\nInvalid URL characters included in the value assigned to the password
property\nare percent-encoded. The selection of which characters to\npercent-encode may vary somewhat from what the url.parse()
and\nurl.format()
methods would produce.
Gets and sets the path portion of the URL.
\nconst myURL = new URL('https://example.org/abc/xyz?123');\nconsole.log(myURL.pathname);\n// Prints /abc/xyz\n\nmyURL.pathname = '/abcdef';\nconsole.log(myURL.href);\n// Prints https://example.org/abcdef?123\n
\nInvalid URL characters included in the value assigned to the pathname
\nproperty are percent-encoded. The selection of which characters\nto percent-encode may vary somewhat from what the url.parse()
and\nurl.format()
methods would produce.
Gets and sets the port portion of the URL.
\nThe port value may be a number or a string containing a number in the range\n0
to 65535
(inclusive). Setting the value to the default port of the\nURL
objects given protocol
will result in the port
value becoming\nthe empty string (''
).
The port value can be an empty string in which case the port depends on\nthe protocol/scheme:
\nprotocol | \nport | \n
---|---|
\"ftp\" | \n21 | \n
\"file\" | \n\n |
\"gopher\" | \n70 | \n
\"http\" | \n80 | \n
\"https\" | \n443 | \n
\"ws\" | \n80 | \n
\"wss\" | \n443 | \n
Upon assigning a value to the port, the value will first be converted to a\nstring using .toString()
.
If that string is invalid but it begins with a number, the leading number is\nassigned to port
.\nIf the number lies outside the range denoted above, it is ignored.
const myURL = new URL('https://example.org:8888');\nconsole.log(myURL.port);\n// Prints 8888\n\n// Default ports are automatically transformed to the empty string\n// (HTTPS protocol's default port is 443)\nmyURL.port = '443';\nconsole.log(myURL.port);\n// Prints the empty string\nconsole.log(myURL.href);\n// Prints https://example.org/\n\nmyURL.port = 1234;\nconsole.log(myURL.port);\n// Prints 1234\nconsole.log(myURL.href);\n// Prints https://example.org:1234/\n\n// Completely invalid port strings are ignored\nmyURL.port = 'abcd';\nconsole.log(myURL.port);\n// Prints 1234\n\n// Leading numbers are treated as a port number\nmyURL.port = '5678abcd';\nconsole.log(myURL.port);\n// Prints 5678\n\n// Non-integers are truncated\nmyURL.port = 1234.5678;\nconsole.log(myURL.port);\n// Prints 1234\n\n// Out-of-range numbers which are not represented in scientific notation\n// will be ignored.\nmyURL.port = 1e10; // 10000000000, will be range-checked as described below\nconsole.log(myURL.port);\n// Prints 1234\n
\nNumbers which contain a decimal point,\nsuch as floating-point numbers or numbers in scientific notation,\nare not an exception to this rule.\nLeading numbers up to the decimal point will be set as the URL's port,\nassuming they are valid:
\nmyURL.port = 4.567e21;\nconsole.log(myURL.port);\n// Prints 4 (because it is the leading number in the string '4.567e21')\n
"
},
{
"textRaw": "`protocol` {string}",
"type": "string",
"name": "protocol",
"desc": "Gets and sets the protocol portion of the URL.
\nconst myURL = new URL('https://example.org');\nconsole.log(myURL.protocol);\n// Prints https:\n\nmyURL.protocol = 'ftp';\nconsole.log(myURL.href);\n// Prints ftp://example.org/\n
\nInvalid URL protocol values assigned to the protocol
property are ignored.
The WHATWG URL Standard considers a handful of URL protocol schemes to be\nspecial in terms of how they are parsed and serialized. When a URL is\nparsed using one of these special protocols, the url.protocol
property\nmay be changed to another special protocol but cannot be changed to a\nnon-special protocol, and vice versa.
For instance, changing from http
to https
works:
const u = new URL('http://example.org');\nu.protocol = 'https';\nconsole.log(u.href);\n// https://example.org\n
\nHowever, changing from http
to a hypothetical fish
protocol does not\nbecause the new protocol is not special.
const u = new URL('http://example.org');\nu.protocol = 'fish';\nconsole.log(u.href);\n// http://example.org\n
\nLikewise, changing from a non-special protocol to a special protocol is also\nnot permitted:
\nconst u = new URL('fish://example.org');\nu.protocol = 'http';\nconsole.log(u.href);\n// fish://example.org\n
\nAccording to the WHATWG URL Standard, special protocol schemes are ftp
,\nfile
, gopher
, http
, https
, ws
, and wss
.
Gets and sets the serialized query portion of the URL.
\nconst myURL = new URL('https://example.org/abc?123');\nconsole.log(myURL.search);\n// Prints ?123\n\nmyURL.search = 'abc=xyz';\nconsole.log(myURL.href);\n// Prints https://example.org/abc?abc=xyz\n
\nAny invalid URL characters appearing in the value assigned the search
\nproperty will be percent-encoded. The selection of which\ncharacters to percent-encode may vary somewhat from what the url.parse()
\nand url.format()
methods would produce.
Gets the URLSearchParams
object representing the query parameters of the\nURL. This property is read-only but the URLSearchParams
object it provides\ncan be used to mutate the URL instance; to replace the entirety of query\nparameters of the URL, use the url.search
setter. See\nURLSearchParams
documentation for details.
Use care when using .searchParams
to modify the URL
because,\nper the WHATWG specification, the URLSearchParams
object uses\ndifferent rules to determine which characters to percent-encode. For\ninstance, the URL
object will not percent encode the ASCII tilde (~
)\ncharacter, while URLSearchParams
will always encode it:
const myUrl = new URL('https://example.org/abc?foo=~bar');\n\nconsole.log(myUrl.search); // prints ?foo=~bar\n\n// Modify the URL via searchParams...\nmyUrl.searchParams.sort();\n\nconsole.log(myUrl.search); // prints ?foo=%7Ebar\n
"
},
{
"textRaw": "`username` {string}",
"type": "string",
"name": "username",
"desc": "Gets and sets the username portion of the URL.
\nconst myURL = new URL('https://abc:xyz@example.com');\nconsole.log(myURL.username);\n// Prints abc\n\nmyURL.username = '123';\nconsole.log(myURL.href);\n// Prints https://123:xyz@example.com/\n
\nAny invalid URL characters appearing in the value assigned the username
\nproperty will be percent-encoded. The selection of which\ncharacters to percent-encode may vary somewhat from what the url.parse()
\nand url.format()
methods would produce.
The toString()
method on the URL
object returns the serialized URL. The\nvalue returned is equivalent to that of url.href
and url.toJSON()
.
Because of the need for standard compliance, this method does not allow users\nto customize the serialization process of the URL. For more flexibility,\nrequire('url').format()
method might be of interest.
The toJSON()
method on the URL
object returns the serialized URL. The\nvalue returned is equivalent to that of url.href
and\nurl.toString()
.
This method is automatically called when an URL
object is serialized\nwith JSON.stringify()
.
const myURLs = [\n new URL('https://www.example.com'),\n new URL('https://test.example.org'),\n];\nconsole.log(JSON.stringify(myURLs));\n// Prints [\"https://www.example.com/\",\"https://test.example.org/\"]\n
"
}
],
"signatures": [
{
"params": [
{
"textRaw": "`input` {string} The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored.",
"name": "input",
"type": "string",
"desc": "The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored."
},
{
"textRaw": "`base` {string|URL} The base URL to resolve against if the `input` is not absolute.",
"name": "base",
"type": "string|URL",
"desc": "The base URL to resolve against if the `input` is not absolute."
}
],
"desc": "Creates a new URL
object by parsing the input
relative to the base
. If\nbase
is passed as a string, it will be parsed equivalent to new URL(base)
.
const myURL = new URL('/foo', 'https://example.org/');\n// https://example.org/foo\n
\nThe URL constructor is accessible as a property on the global object.\nIt can also be imported from the built-in url module:
\nconsole.log(URL === require('url').URL); // Prints 'true'.\n
\nA TypeError
will be thrown if the input
or base
are not valid URLs. Note\nthat an effort will be made to coerce the given values into strings. For\ninstance:
const myURL = new URL({ toString: () => 'https://example.org/' });\n// https://example.org/\n
\nUnicode characters appearing within the host name of input
will be\nautomatically converted to ASCII using the Punycode algorithm.
const myURL = new URL('https://測試');\n// https://xn--g6w251d/\n
\nThis feature is only available if the node
executable was compiled with\nICU enabled. If not, the domain names are passed through unchanged.
In cases where it is not known in advance if input
is an absolute URL\nand a base
is provided, it is advised to validate that the origin
of\nthe URL
object is what is expected.
let myURL = new URL('http://Example.com/', 'https://example.org/');\n// http://example.com/\n\nmyURL = new URL('https://Example.com/', 'https://example.org/');\n// https://example.com/\n\nmyURL = new URL('foo://Example.com/', 'https://example.org/');\n// foo://Example.com/\n\nmyURL = new URL('http:Example.com/', 'https://example.org/');\n// http://example.com/\n\nmyURL = new URL('https:Example.com/', 'https://example.org/');\n// https://example.org/Example.com/\n\nmyURL = new URL('foo:Example.com/', 'https://example.org/');\n// foo:Example.com/\n
"
}
]
},
{
"textRaw": "Class: `URLSearchParams`",
"type": "class",
"name": "URLSearchParams",
"meta": {
"added": [
"v7.5.0",
"v6.13.0"
],
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18281",
"description": "The class is now available on the global object."
}
]
},
"desc": "The URLSearchParams
API provides read and write access to the query of a\nURL
. The URLSearchParams
class can also be used standalone with one of the\nfour following constructors.\nThe URLSearchParams
class is also available on the global object.
The WHATWG URLSearchParams
interface and the querystring
module have\nsimilar purpose, but the purpose of the querystring
module is more\ngeneral, as it allows the customization of delimiter characters (&
and =
).\nOn the other hand, this API is designed purely for URL query strings.
const myURL = new URL('https://example.org/?abc=123');\nconsole.log(myURL.searchParams.get('abc'));\n// Prints 123\n\nmyURL.searchParams.append('abc', 'xyz');\nconsole.log(myURL.href);\n// Prints https://example.org/?abc=123&abc=xyz\n\nmyURL.searchParams.delete('abc');\nmyURL.searchParams.set('a', 'b');\nconsole.log(myURL.href);\n// Prints https://example.org/?a=b\n\nconst newSearchParams = new URLSearchParams(myURL.searchParams);\n// The above is equivalent to\n// const newSearchParams = new URLSearchParams(myURL.search);\n\nnewSearchParams.append('a', 'c');\nconsole.log(myURL.href);\n// Prints https://example.org/?a=b\nconsole.log(newSearchParams.toString());\n// Prints a=b&a=c\n\n// newSearchParams.toString() is implicitly called\nmyURL.search = newSearchParams;\nconsole.log(myURL.href);\n// Prints https://example.org/?a=b&a=c\nnewSearchParams.delete('a');\nconsole.log(myURL.href);\n// Prints https://example.org/?a=b&a=c\n
",
"methods": [
{
"textRaw": "`urlSearchParams.append(name, value)`",
"type": "method",
"name": "append",
"signatures": [
{
"params": [
{
"textRaw": "`name` {string}",
"name": "name",
"type": "string"
},
{
"textRaw": "`value` {string}",
"name": "value",
"type": "string"
}
]
}
],
"desc": "Append a new name-value pair to the query string.
" }, { "textRaw": "`urlSearchParams.delete(name)`", "type": "method", "name": "delete", "signatures": [ { "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" } ] } ], "desc": "Remove all name-value pairs whose name is name
.
Returns an ES6 Iterator
over each of the name-value pairs in the query.\nEach item of the iterator is a JavaScript Array
. The first item of the Array
\nis the name
, the second item of the Array
is the value
.
Alias for urlSearchParams[@@iterator]()
.
Iterates over each name-value pair in the query and invokes the given function.
\nconst myURL = new URL('https://example.org/?a=b&c=d');\nmyURL.searchParams.forEach((value, name, searchParams) => {\n console.log(name, value, myURL.searchParams === searchParams);\n});\n// Prints:\n// a b true\n// c d true\n
"
},
{
"textRaw": "`urlSearchParams.get(name)`",
"type": "method",
"name": "get",
"signatures": [
{
"return": {
"textRaw": "Returns: {string} or `null` if there is no name-value pair with the given `name`.",
"name": "return",
"type": "string",
"desc": "or `null` if there is no name-value pair with the given `name`."
},
"params": [
{
"textRaw": "`name` {string}",
"name": "name",
"type": "string"
}
]
}
],
"desc": "Returns the value of the first name-value pair whose name is name
. If there\nare no such pairs, null
is returned.
Returns the values of all name-value pairs whose name is name
. If there are\nno such pairs, an empty array is returned.
Returns true
if there is at least one name-value pair whose name is name
.
Returns an ES6 Iterator
over the names of each name-value pair.
const params = new URLSearchParams('foo=bar&foo=baz');\nfor (const name of params.keys()) {\n console.log(name);\n}\n// Prints:\n// foo\n// foo\n
"
},
{
"textRaw": "`urlSearchParams.set(name, value)`",
"type": "method",
"name": "set",
"signatures": [
{
"params": [
{
"textRaw": "`name` {string}",
"name": "name",
"type": "string"
},
{
"textRaw": "`value` {string}",
"name": "value",
"type": "string"
}
]
}
],
"desc": "Sets the value in the URLSearchParams
object associated with name
to\nvalue
. If there are any pre-existing name-value pairs whose names are name
,\nset the first such pair's value to value
and remove all others. If not,\nappend the name-value pair to the query string.
const params = new URLSearchParams();\nparams.append('foo', 'bar');\nparams.append('foo', 'baz');\nparams.append('abc', 'def');\nconsole.log(params.toString());\n// Prints foo=bar&foo=baz&abc=def\n\nparams.set('foo', 'def');\nparams.set('xyz', 'opq');\nconsole.log(params.toString());\n// Prints foo=def&abc=def&xyz=opq\n
"
},
{
"textRaw": "`urlSearchParams.sort()`",
"type": "method",
"name": "sort",
"meta": {
"added": [
"v7.7.0",
"v6.13.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "Sort all existing name-value pairs in-place by their names. Sorting is done\nwith a stable sorting algorithm, so relative order between name-value pairs\nwith the same name is preserved.
\nThis method can be used, in particular, to increase cache hits.
\nconst params = new URLSearchParams('query[]=abc&type=search&query[]=123');\nparams.sort();\nconsole.log(params.toString());\n// Prints query%5B%5D=abc&query%5B%5D=123&type=search\n
"
},
{
"textRaw": "`urlSearchParams.toString()`",
"type": "method",
"name": "toString",
"signatures": [
{
"return": {
"textRaw": "Returns: {string}",
"name": "return",
"type": "string"
},
"params": []
}
],
"desc": "Returns the search parameters serialized as a string, with characters\npercent-encoded where necessary.
" }, { "textRaw": "`urlSearchParams.values()`", "type": "method", "name": "values", "signatures": [ { "return": { "textRaw": "Returns: {Iterator}", "name": "return", "type": "Iterator" }, "params": [] } ], "desc": "Returns an ES6 Iterator
over the values of each name-value pair.
Returns an ES6 Iterator
over each of the name-value pairs in the query string.\nEach item of the iterator is a JavaScript Array
. The first item of the Array
\nis the name
, the second item of the Array
is the value
.
Alias for urlSearchParams.entries()
.
const params = new URLSearchParams('foo=bar&xyz=baz');\nfor (const [name, value] of params) {\n console.log(name, value);\n}\n// Prints:\n// foo bar\n// xyz baz\n
"
}
],
"signatures": [
{
"params": [],
"desc": "Instantiate a new empty URLSearchParams
object.
Parse the string
as a query string, and use it to instantiate a new\nURLSearchParams
object. A leading '?'
, if present, is ignored.
let params;\n\nparams = new URLSearchParams('user=abc&query=xyz');\nconsole.log(params.get('user'));\n// Prints 'abc'\nconsole.log(params.toString());\n// Prints 'user=abc&query=xyz'\n\nparams = new URLSearchParams('?user=abc&query=xyz');\nconsole.log(params.toString());\n// Prints 'user=abc&query=xyz'\n
"
},
{
"params": [
{
"textRaw": "`obj` {Object} An object representing a collection of key-value pairs",
"name": "obj",
"type": "Object",
"desc": "An object representing a collection of key-value pairs"
}
],
"desc": "Instantiate a new URLSearchParams
object with a query hash map. The key and\nvalue of each property of obj
are always coerced to strings.
Unlike querystring
module, duplicate keys in the form of array values are\nnot allowed. Arrays are stringified using array.toString()
, which simply\njoins all array elements with commas.
const params = new URLSearchParams({\n user: 'abc',\n query: ['first', 'second']\n});\nconsole.log(params.getAll('query'));\n// Prints [ 'first,second' ]\nconsole.log(params.toString());\n// Prints 'user=abc&query=first%2Csecond'\n
"
},
{
"params": [
{
"textRaw": "`iterable` {Iterable} An iterable object whose elements are key-value pairs",
"name": "iterable",
"type": "Iterable",
"desc": "An iterable object whose elements are key-value pairs"
}
],
"desc": "Instantiate a new URLSearchParams
object with an iterable map in a way that\nis similar to Map
's constructor. iterable
can be an Array
or any\niterable object. That means iterable
can be another URLSearchParams
, in\nwhich case the constructor will simply create a clone of the provided\nURLSearchParams
. Elements of iterable
are key-value pairs, and can\nthemselves be any iterable object.
Duplicate keys are allowed.
\nlet params;\n\n// Using an array\nparams = new URLSearchParams([\n ['user', 'abc'],\n ['query', 'first'],\n ['query', 'second'],\n]);\nconsole.log(params.toString());\n// Prints 'user=abc&query=first&query=second'\n\n// Using a Map object\nconst map = new Map();\nmap.set('user', 'abc');\nmap.set('query', 'xyz');\nparams = new URLSearchParams(map);\nconsole.log(params.toString());\n// Prints 'user=abc&query=xyz'\n\n// Using a generator function\nfunction* getQueryPairs() {\n yield ['user', 'abc'];\n yield ['query', 'first'];\n yield ['query', 'second'];\n}\nparams = new URLSearchParams(getQueryPairs());\nconsole.log(params.toString());\n// Prints 'user=abc&query=first&query=second'\n\n// Each key-value pair must have exactly two elements\nnew URLSearchParams([\n ['user', 'abc', 'error'],\n]);\n// Throws TypeError [ERR_INVALID_TUPLE]:\n// Each query pair must be an iterable [name, value] tuple\n
"
}
]
}
],
"methods": [
{
"textRaw": "`url.domainToASCII(domain)`",
"type": "method",
"name": "domainToASCII",
"meta": {
"added": [
"v7.4.0",
"v6.13.0"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {string}",
"name": "return",
"type": "string"
},
"params": [
{
"textRaw": "`domain` {string}",
"name": "domain",
"type": "string"
}
]
}
],
"desc": "Returns the Punycode ASCII serialization of the domain
. If domain
is an\ninvalid domain, the empty string is returned.
It performs the inverse operation to url.domainToUnicode()
.
This feature is only available if the node
executable was compiled with\nICU enabled. If not, the domain names are passed through unchanged.
const url = require('url');\nconsole.log(url.domainToASCII('español.com'));\n// Prints xn--espaol-zwa.com\nconsole.log(url.domainToASCII('中文.com'));\n// Prints xn--fiq228c.com\nconsole.log(url.domainToASCII('xn--iñvalid.com'));\n// Prints an empty string\n
"
},
{
"textRaw": "`url.domainToUnicode(domain)`",
"type": "method",
"name": "domainToUnicode",
"meta": {
"added": [
"v7.4.0",
"v6.13.0"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {string}",
"name": "return",
"type": "string"
},
"params": [
{
"textRaw": "`domain` {string}",
"name": "domain",
"type": "string"
}
]
}
],
"desc": "Returns the Unicode serialization of the domain
. If domain
is an invalid\ndomain, the empty string is returned.
It performs the inverse operation to url.domainToASCII()
.
This feature is only available if the node
executable was compiled with\nICU enabled. If not, the domain names are passed through unchanged.
const url = require('url');\nconsole.log(url.domainToUnicode('xn--espaol-zwa.com'));\n// Prints español.com\nconsole.log(url.domainToUnicode('xn--fiq228c.com'));\n// Prints 中文.com\nconsole.log(url.domainToUnicode('xn--iñvalid.com'));\n// Prints an empty string\n
"
},
{
"textRaw": "`url.fileURLToPath(url)`",
"type": "method",
"name": "fileURLToPath",
"meta": {
"added": [
"v10.12.0"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {string} The fully-resolved platform-specific Node.js file path.",
"name": "return",
"type": "string",
"desc": "The fully-resolved platform-specific Node.js file path."
},
"params": [
{
"textRaw": "`url` {URL | string} The file URL string or URL object to convert to a path.",
"name": "url",
"type": "URL | string",
"desc": "The file URL string or URL object to convert to a path."
}
]
}
],
"desc": "This function ensures the correct decodings of percent-encoded characters as\nwell as ensuring a cross-platform valid absolute path string.
\nimport { fileURLToPath } from 'url';\n\nconst __filename = fileURLToPath(import.meta.url);\n\nnew URL('file:///C:/path/').pathname; // Incorrect: /C:/path/\nfileURLToPath('file:///C:/path/'); // Correct: C:\\path\\ (Windows)\n\nnew URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt\nfileURLToPath('file://nas/foo.txt'); // Correct: \\\\nas\\foo.txt (Windows)\n\nnew URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt\nfileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX)\n\nnew URL('file:///hello world').pathname; // Incorrect: /hello%20world\nfileURLToPath('file:///hello world'); // Correct: /hello world (POSIX)\n
\nconst { fileURLToPath } = require('url');\nnew URL('file:///C:/path/').pathname; // Incorrect: /C:/path/\nfileURLToPath('file:///C:/path/'); // Correct: C:\\path\\ (Windows)\n\nnew URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt\nfileURLToPath('file://nas/foo.txt'); // Correct: \\\\nas\\foo.txt (Windows)\n\nnew URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt\nfileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX)\n\nnew URL('file:///hello world').pathname; // Incorrect: /hello%20world\nfileURLToPath('file:///hello world'); // Correct: /hello world (POSIX)\n
"
},
{
"textRaw": "`url.format(URL[, options])`",
"type": "method",
"name": "format",
"meta": {
"added": [
"v7.6.0"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {string}",
"name": "return",
"type": "string"
},
"params": [
{
"textRaw": "`URL` {URL} A [WHATWG URL][] object",
"name": "URL",
"type": "URL",
"desc": "A [WHATWG URL][] object"
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`auth` {boolean} `true` if the serialized URL string should include the username and password, `false` otherwise. **Default:** `true`.",
"name": "auth",
"type": "boolean",
"default": "`true`",
"desc": "`true` if the serialized URL string should include the username and password, `false` otherwise."
},
{
"textRaw": "`fragment` {boolean} `true` if the serialized URL string should include the fragment, `false` otherwise. **Default:** `true`.",
"name": "fragment",
"type": "boolean",
"default": "`true`",
"desc": "`true` if the serialized URL string should include the fragment, `false` otherwise."
},
{
"textRaw": "`search` {boolean} `true` if the serialized URL string should include the search query, `false` otherwise. **Default:** `true`.",
"name": "search",
"type": "boolean",
"default": "`true`",
"desc": "`true` if the serialized URL string should include the search query, `false` otherwise."
},
{
"textRaw": "`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. **Default:** `false`.",
"name": "unicode",
"type": "boolean",
"default": "`false`",
"desc": "`true` if Unicode characters appearing in the host component of the URL string should be encoded directly as opposed to being Punycode encoded."
}
]
}
]
}
],
"desc": "Returns a customizable serialization of a URL String
representation of a\nWHATWG URL object.
The URL object has both a toString()
method and href
property that return\nstring serializations of the URL. These are not, however, customizable in\nany way. The url.format(URL[, options])
method allows for basic customization\nof the output.
import url from 'url';\nconst myURL = new URL('https://a:b@測試?abc#foo');\n\nconsole.log(myURL.href);\n// Prints https://a:b@xn--g6w251d/?abc#foo\n\nconsole.log(myURL.toString());\n// Prints https://a:b@xn--g6w251d/?abc#foo\n\nconsole.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));\n// Prints 'https://測試/?abc'\n
\nconst url = require('url');\nconst myURL = new URL('https://a:b@測試?abc#foo');\n\nconsole.log(myURL.href);\n// Prints https://a:b@xn--g6w251d/?abc#foo\n\nconsole.log(myURL.toString());\n// Prints https://a:b@xn--g6w251d/?abc#foo\n\nconsole.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));\n// Prints 'https://測試/?abc'\n
"
},
{
"textRaw": "`url.pathToFileURL(path)`",
"type": "method",
"name": "pathToFileURL",
"meta": {
"added": [
"v10.12.0"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {URL} The file URL object.",
"name": "return",
"type": "URL",
"desc": "The file URL object."
},
"params": [
{
"textRaw": "`path` {string} The path to convert to a File URL.",
"name": "path",
"type": "string",
"desc": "The path to convert to a File URL."
}
]
}
],
"desc": "This function ensures that path
is resolved absolutely, and that the URL\ncontrol characters are correctly encoded when converting into a File URL.
import { pathToFileURL } from 'url';\n\nnew URL('/foo#1', 'file:'); // Incorrect: file:///foo#1\npathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX)\n\nnew URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c\npathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX)\n
\nconst { pathToFileURL } = require('url');\nnew URL(__filename); // Incorrect: throws (POSIX)\nnew URL(__filename); // Incorrect: C:\\... (Windows)\npathToFileURL(__filename); // Correct: file:///... (POSIX)\npathToFileURL(__filename); // Correct: file:///C:/... (Windows)\n\nnew URL('/foo#1', 'file:'); // Incorrect: file:///foo#1\npathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX)\n\nnew URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c\npathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX)\n
"
},
{
"textRaw": "`url.urlToHttpOptions(url)`",
"type": "method",
"name": "urlToHttpOptions",
"meta": {
"added": [
"v14.18.0"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Object} Options object",
"name": "return",
"type": "Object",
"desc": "Options object",
"options": [
{
"textRaw": "`protocol` {string} Protocol to use.",
"name": "protocol",
"type": "string",
"desc": "Protocol to use."
},
{
"textRaw": "`hostname` {string} A domain name or IP address of the server to issue the request to.",
"name": "hostname",
"type": "string",
"desc": "A domain name or IP address of the server to issue the request to."
},
{
"textRaw": "`hash` {string} The fragment portion of the URL.",
"name": "hash",
"type": "string",
"desc": "The fragment portion of the URL."
},
{
"textRaw": "`search` {string} The serialized query portion of the URL.",
"name": "search",
"type": "string",
"desc": "The serialized query portion of the URL."
},
{
"textRaw": "`pathname` {string} The path portion of the URL.",
"name": "pathname",
"type": "string",
"desc": "The path portion of the URL."
},
{
"textRaw": "`path` {string} Request path. Should include query string if any. E.G. `'/index.html?page=12'`. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future.",
"name": "path",
"type": "string",
"desc": "Request path. Should include query string if any. E.G. `'/index.html?page=12'`. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future."
},
{
"textRaw": "`href` {string} The serialized URL.",
"name": "href",
"type": "string",
"desc": "The serialized URL."
},
{
"textRaw": "`port` {number} Port of remote server.",
"name": "port",
"type": "number",
"desc": "Port of remote server."
},
{
"textRaw": "`auth` {string} Basic authentication i.e. `'user:password'` to compute an Authorization header.",
"name": "auth",
"type": "string",
"desc": "Basic authentication i.e. `'user:password'` to compute an Authorization header."
}
]
},
"params": [
{
"textRaw": "`url` {URL} The [WHATWG URL][] object to convert to an options object.",
"name": "url",
"type": "URL",
"desc": "The [WHATWG URL][] object to convert to an options object."
}
]
}
],
"desc": "This utility function converts a URL object into an ordinary options object as\nexpected by the http.request()
and https.request()
APIs.
const { urlToHttpOptions } = require('url');\nconst myURL = new URL('https://a:b@測試?abc#foo');\n\nconsole.log(urlToHttpOptions(myUrl));\n/**\n{\n protocol: 'https:',\n hostname: 'xn--g6w251d',\n hash: '#foo',\n search: '?abc',\n pathname: '/',\n path: '/?abc',\n href: 'https://a:b@xn--g6w251d/?abc#foo',\n auth: 'a:b'\n}\n*/\n
"
}
],
"type": "module",
"displayName": "The WHATWG URL API"
},
{
"textRaw": "Legacy URL API",
"name": "legacy_url_api",
"meta": {
"changes": [
{
"version": "v14.17.0",
"pr-url": "https://github.com/nodejs/node/pull/37784",
"description": "Deprecation revoked. Status changed to \"Legacy\"."
},
{
"version": "v11.0.0",
"pr-url": "https://github.com/nodejs/node/pull/22715",
"description": "This API is deprecated."
}
]
},
"stability": 3,
"stabilityText": "Legacy: Use the WHATWG URL API instead.",
"modules": [
{
"textRaw": "Legacy `urlObject`",
"name": "legacy_`urlobject`",
"meta": {
"changes": [
{
"version": "v14.17.0",
"pr-url": "https://github.com/nodejs/node/pull/37784",
"description": "Deprecation revoked. Status changed to \"Legacy\"."
},
{
"version": "v11.0.0",
"pr-url": "https://github.com/nodejs/node/pull/22715",
"description": "The Legacy URL API is deprecated. Use the WHATWG URL API."
}
]
},
"stability": 3,
"stabilityText": "Legacy: Use the WHATWG URL API instead.",
"desc": "The legacy urlObject
(require('url').Url
) is created and returned by the\nurl.parse()
function.
The auth
property is the username and password portion of the URL, also\nreferred to as userinfo. This string subset follows the protocol
and\ndouble slashes (if present) and precedes the host
component, delimited by @
.\nThe string is either the username, or it is the username and password separated\nby :
.
For example: 'user:pass'
.
The hash
property is the fragment identifier portion of the URL including the\nleading #
character.
For example: '#hash'
.
The host
property is the full lower-cased host portion of the URL, including\nthe port
if specified.
For example: 'sub.example.com:8080'
.
The hostname
property is the lower-cased host name portion of the host
\ncomponent without the port
included.
For example: 'sub.example.com'
.
The href
property is the full URL string that was parsed with both the\nprotocol
and host
components converted to lower-case.
For example: 'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'
.
The path
property is a concatenation of the pathname
and search
\ncomponents.
For example: '/p/a/t/h?query=string'
.
No decoding of the path
is performed.
The pathname
property consists of the entire path section of the URL. This\nis everything following the host
(including the port
) and before the start\nof the query
or hash
components, delimited by either the ASCII question\nmark (?
) or hash (#
) characters.
For example: '/p/a/t/h'
.
No decoding of the path string is performed.
" }, { "textRaw": "`urlObject.port`", "name": "port", "desc": "The port
property is the numeric port portion of the host
component.
For example: '8080'
.
The protocol
property identifies the URL's lower-cased protocol scheme.
For example: 'http:'
.
The query
property is either the query string without the leading ASCII\nquestion mark (?
), or an object returned by the querystring
module's\nparse()
method. Whether the query
property is a string or object is\ndetermined by the parseQueryString
argument passed to url.parse()
.
For example: 'query=string'
or {'query': 'string'}
.
If returned as a string, no decoding of the query string is performed. If\nreturned as an object, both keys and values are decoded.
" }, { "textRaw": "`urlObject.search`", "name": "search", "desc": "The search
property consists of the entire \"query string\" portion of the\nURL, including the leading ASCII question mark (?
) character.
For example: '?query=string'
.
No decoding of the query string is performed.
" }, { "textRaw": "`urlObject.slashes`", "name": "slashes", "desc": "The slashes
property is a boolean
with a value of true
if two ASCII\nforward-slash characters (/
) are required following the colon in the\nprotocol
.
The url.format()
method returns a formatted URL string derived from\nurlObject
.
const url = require('url');\nurl.format({\n protocol: 'https',\n hostname: 'example.com',\n pathname: '/some/path',\n query: {\n page: 1,\n format: 'json'\n }\n});\n\n// => 'https://example.com/some/path?page=1&format=json'\n
\nIf urlObject
is not an object or a string, url.format()
will throw a\nTypeError
.
The formatting process operates as follows:
\nresult
is created.urlObject.protocol
is a string, it is appended as-is to result
.urlObject.protocol
is not undefined
and is not a string, an\nError
is thrown.urlObject.protocol
that do not end with an ASCII\ncolon (:
) character, the literal string :
will be appended to result
.//
\nwill be appended to result
:\nurlObject.slashes
property is true;urlObject.protocol
begins with http
, https
, ftp
, gopher
, or\nfile
;urlObject.auth
property is truthy, and either\nurlObject.host
or urlObject.hostname
are not undefined
, the value of\nurlObject.auth
will be coerced into a string and appended to result
\nfollowed by the literal string @
.urlObject.host
property is undefined
then:\nurlObject.hostname
is a string, it is appended to result
.urlObject.hostname
is not undefined
and is not a string,\nan Error
is thrown.urlObject.port
property value is truthy, and urlObject.hostname
\nis not undefined
:\n:
is appended to result
, andurlObject.port
is coerced to a string and appended to\nresult
.urlObject.host
property value is truthy, the value of\nurlObject.host
is coerced to a string and appended to result
.urlObject.pathname
property is a string that is not an empty string:\nurlObject.pathname
does not start with an ASCII forward slash\n(/
), then the literal string '/'
is appended to result
.urlObject.pathname
is appended to result
.urlObject.pathname
is not undefined
and is not a string, an\nError
is thrown.urlObject.search
property is undefined
and if the urlObject.query
\nproperty is an Object
, the literal string ?
is appended to result
\nfollowed by the output of calling the querystring
module's stringify()
\nmethod passing the value of urlObject.query
.urlObject.search
is a string:\nurlObject.search
does not start with the ASCII question\nmark (?
) character, the literal string ?
is appended to result
.urlObject.search
is appended to result
.urlObject.search
is not undefined
and is not a string, an\nError
is thrown.urlObject.hash
property is a string:\nurlObject.hash
does not start with the ASCII hash (#
)\ncharacter, the literal string #
is appended to result
.urlObject.hash
is appended to result
.urlObject.hash
property is not undefined
and is not a\nstring, an Error
is thrown.result
is returned.The url.parse()
method takes a URL string, parses it, and returns a URL\nobject.
A TypeError
is thrown if urlString
is not a string.
A URIError
is thrown if the auth
property is present but cannot be decoded.
Use of the legacy url.parse()
method is discouraged. Users should\nuse the WHATWG URL
API. Because the url.parse()
method uses a\nlenient, non-standard algorithm for parsing URL strings, security\nissues can be introduced. Specifically, issues with host name spoofing and\nincorrect handling of usernames and passwords have been identified.
The url.resolve()
method resolves a target URL relative to a base URL in a\nmanner similar to that of a Web browser resolving an anchor tag HREF.
const url = require('url');\nurl.resolve('/one/two/three', 'four'); // '/one/two/four'\nurl.resolve('http://example.com/', '/one'); // 'http://example.com/one'\nurl.resolve('http://example.com/one', '/two'); // 'http://example.com/two'\n
\nYou can achieve the same result using the WHATWG URL API:
\nfunction resolve(from, to) {\n const resolvedUrl = new URL(to, new URL(from, 'resolve://'));\n if (resolvedUrl.protocol === 'resolve:') {\n // `from` is a relative URL.\n const { pathname, search, hash } = resolvedUrl;\n return pathname + search + hash;\n }\n return resolvedUrl.toString();\n}\n\nresolve('/one/two/three', 'four'); // '/one/two/four'\nresolve('http://example.com/', '/one'); // 'http://example.com/one'\nresolve('http://example.com/one', '/two'); // 'http://example.com/two'\n
\n"
}
],
"type": "module",
"displayName": "Legacy URL API"
},
{
"textRaw": "Percent-encoding in URLs",
"name": "percent-encoding_in_urls",
"desc": "URLs are permitted to only contain a certain range of characters. Any character\nfalling outside of that range must be encoded. How such characters are encoded,\nand which characters to encode depends entirely on where the character is\nlocated within the structure of the URL.
", "modules": [ { "textRaw": "Legacy API", "name": "legacy_api", "desc": "Within the Legacy API, spaces (' '
) and the following characters will be\nautomatically escaped in the properties of URL objects:
< > \" ` \\r \\n \\t { } | \\ ^ '\n
\nFor example, the ASCII space character (' '
) is encoded as %20
. The ASCII\nforward slash (/
) character is encoded as %3C
.
The WHATWG URL Standard uses a more selective and fine grained approach to\nselecting encoded characters than that used by the Legacy API.
\nThe WHATWG algorithm defines four \"percent-encode sets\" that describe ranges\nof characters that must be percent-encoded:
\nThe C0 control percent-encode set includes code points in range U+0000 to\nU+001F (inclusive) and all code points greater than U+007E.
\nThe fragment percent-encode set includes the C0 control percent-encode set\nand code points U+0020, U+0022, U+003C, U+003E, and U+0060.
\nThe path percent-encode set includes the C0 control percent-encode set\nand code points U+0020, U+0022, U+0023, U+003C, U+003E, U+003F, U+0060,\nU+007B, and U+007D.
\nThe userinfo encode set includes the path percent-encode set and code\npoints U+002F, U+003A, U+003B, U+003D, U+0040, U+005B, U+005C, U+005D,\nU+005E, and U+007C.
\nThe userinfo percent-encode set is used exclusively for username and\npasswords encoded within the URL. The path percent-encode set is used for the\npath of most URLs. The fragment percent-encode set is used for URL fragments.\nThe C0 control percent-encode set is used for host and path under certain\nspecific conditions, in addition to all other cases.
\nWhen non-ASCII characters appear within a host name, the host name is encoded\nusing the Punycode algorithm. Note, however, that a host name may contain\nboth Punycode encoded and percent-encoded characters:
\nconst myURL = new URL('https://%CF%80.example.com/foo');\nconsole.log(myURL.href);\n// Prints https://xn--1xa.example.com/foo\nconsole.log(myURL.origin);\n// Prints https://xn--1xa.example.com\n
",
"type": "module",
"displayName": "WHATWG API"
}
],
"type": "module",
"displayName": "Percent-encoding in URLs"
}
],
"type": "module",
"displayName": "URL"
}
]
}