• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# URL
2
3<!--introduced_in=v0.10.0-->
4
5> Stability: 2 - Stable
6
7<!-- source_link=lib/url.js -->
8
9The `url` module provides utilities for URL resolution and parsing. It can be
10accessed using:
11
12```js
13const url = require('url');
14```
15
16## URL strings and URL objects
17
18A URL string is a structured string containing multiple meaningful components.
19When parsed, a URL object is returned containing properties for each of these
20components.
21
22The `url` module provides two APIs for working with URLs: a legacy API that is
23Node.js specific, and a newer API that implements the same
24[WHATWG URL Standard][] used by web browsers.
25
26A comparison between the WHATWG and Legacy APIs is provided below. Above the URL
27`'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'`, properties
28of an object returned by the legacy `url.parse()` are shown. Below it are
29properties of a WHATWG `URL` object.
30
31WHATWG URL's `origin` property includes `protocol` and `host`, but not
32`username` or `password`.
33
34```text
35┌────────────────────────────────────────────────────────────────────────────────────────────────┐
36│                                              href                                              │
37├──────────┬──┬─────────────────────┬────────────────────────┬───────────────────────────┬───────┤
38│ protocol │  │        auth         │          host          │           path            │ hash  │
39│          │  │                     ├─────────────────┬──────┼──────────┬────────────────┤       │
40│          │  │                     │    hostname     │ port │ pathname │     search     │       │
41│          │  │                     │                 │      │          ├─┬──────────────┤       │
42│          │  │                     │                 │      │          │ │    query     │       │
43"  https:   //    user   :   pass   @ sub.example.com : 8080   /p/a/t/h  ?  query=string   #hash "
44│          │  │          │          │    hostname     │ port │          │                │       │
45│          │  │          │          ├─────────────────┴──────┤          │                │       │
46│ protocol │  │ username │ password │          host          │          │                │       │
47├──────────┴──┼──────────┴──────────┼────────────────────────┤          │                │       │
48│   origin    │                     │         origin         │ pathname │     search     │ hash  │
49├─────────────┴─────────────────────┴────────────────────────┴──────────┴────────────────┴───────┤
50│                                              href                                              │
51└────────────────────────────────────────────────────────────────────────────────────────────────┘
52(All spaces in the "" line should be ignored. They are purely for formatting.)
53```
54
55Parsing the URL string using the WHATWG API:
56
57```js
58const myURL =
59  new URL('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');
60```
61
62Parsing the URL string using the Legacy API:
63
64```js
65const url = require('url');
66const myURL =
67  url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');
68```
69
70## The WHATWG URL API
71
72### Class: `URL`
73<!-- YAML
74added:
75  - v7.0.0
76  - v6.13.0
77changes:
78  - version: v10.0.0
79    pr-url: https://github.com/nodejs/node/pull/18281
80    description: The class is now available on the global object.
81-->
82
83Browser-compatible `URL` class, implemented by following the WHATWG URL
84Standard. [Examples of parsed URLs][] may be found in the Standard itself.
85The `URL` class is also available on the global object.
86
87In accordance with browser conventions, all properties of `URL` objects
88are implemented as getters and setters on the class prototype, rather than as
89data properties on the object itself. Thus, unlike [legacy `urlObject`][]s,
90using the `delete` keyword on any properties of `URL` objects (e.g. `delete
91myURL.protocol`, `delete myURL.pathname`, etc) has no effect but will still
92return `true`.
93
94#### `new URL(input[, base])`
95
96* `input` {string} The absolute or relative input URL to parse. If `input`
97  is relative, then `base` is required. If `input` is absolute, the `base`
98  is ignored.
99* `base` {string|URL} The base URL to resolve against if the `input` is not
100  absolute.
101
102Creates a new `URL` object by parsing the `input` relative to the `base`. If
103`base` is passed as a string, it will be parsed equivalent to `new URL(base)`.
104
105```js
106const myURL = new URL('/foo', 'https://example.org/');
107// https://example.org/foo
108```
109
110The URL constructor is accessible as a property on the global object.
111It can also be imported from the built-in url module:
112
113```js
114console.log(URL === require('url').URL); // Prints 'true'.
115```
116
117A `TypeError` will be thrown if the `input` or `base` are not valid URLs. Note
118that an effort will be made to coerce the given values into strings. For
119instance:
120
121```js
122const myURL = new URL({ toString: () => 'https://example.org/' });
123// https://example.org/
124```
125
126Unicode characters appearing within the host name of `input` will be
127automatically converted to ASCII using the [Punycode][] algorithm.
128
129```js
130const myURL = new URL('https://測試');
131// https://xn--g6w251d/
132```
133
134This feature is only available if the `node` executable was compiled with
135[ICU][] enabled. If not, the domain names are passed through unchanged.
136
137In cases where it is not known in advance if `input` is an absolute URL
138and a `base` is provided, it is advised to validate that the `origin` of
139the `URL` object is what is expected.
140
141```js
142let myURL = new URL('http://Example.com/', 'https://example.org/');
143// http://example.com/
144
145myURL = new URL('https://Example.com/', 'https://example.org/');
146// https://example.com/
147
148myURL = new URL('foo://Example.com/', 'https://example.org/');
149// foo://Example.com/
150
151myURL = new URL('http:Example.com/', 'https://example.org/');
152// http://example.com/
153
154myURL = new URL('https:Example.com/', 'https://example.org/');
155// https://example.org/Example.com/
156
157myURL = new URL('foo:Example.com/', 'https://example.org/');
158// foo:Example.com/
159```
160
161#### `url.hash`
162
163* {string}
164
165Gets and sets the fragment portion of the URL.
166
167```js
168const myURL = new URL('https://example.org/foo#bar');
169console.log(myURL.hash);
170// Prints #bar
171
172myURL.hash = 'baz';
173console.log(myURL.href);
174// Prints https://example.org/foo#baz
175```
176
177Invalid URL characters included in the value assigned to the `hash` property
178are [percent-encoded][]. The selection of which characters to
179percent-encode may vary somewhat from what the [`url.parse()`][] and
180[`url.format()`][] methods would produce.
181
182#### `url.host`
183
184* {string}
185
186Gets and sets the host portion of the URL.
187
188```js
189const myURL = new URL('https://example.org:81/foo');
190console.log(myURL.host);
191// Prints example.org:81
192
193myURL.host = 'example.com:82';
194console.log(myURL.href);
195// Prints https://example.com:82/foo
196```
197
198Invalid host values assigned to the `host` property are ignored.
199
200#### `url.hostname`
201
202* {string}
203
204Gets and sets the host name portion of the URL. The key difference between
205`url.host` and `url.hostname` is that `url.hostname` does *not* include the
206port.
207
208```js
209const myURL = new URL('https://example.org:81/foo');
210console.log(myURL.hostname);
211// Prints example.org
212
213myURL.hostname = 'example.com:82';
214console.log(myURL.href);
215// Prints https://example.com:81/foo
216```
217
218Invalid host name values assigned to the `hostname` property are ignored.
219
220#### `url.href`
221
222* {string}
223
224Gets and sets the serialized URL.
225
226```js
227const myURL = new URL('https://example.org/foo');
228console.log(myURL.href);
229// Prints https://example.org/foo
230
231myURL.href = 'https://example.com/bar';
232console.log(myURL.href);
233// Prints https://example.com/bar
234```
235
236Getting the value of the `href` property is equivalent to calling
237[`url.toString()`][].
238
239Setting the value of this property to a new value is equivalent to creating a
240new `URL` object using [`new URL(value)`][`new URL()`]. Each of the `URL`
241object's properties will be modified.
242
243If the value assigned to the `href` property is not a valid URL, a `TypeError`
244will be thrown.
245
246#### `url.origin`
247
248* {string}
249
250Gets the read-only serialization of the URL's origin.
251
252```js
253const myURL = new URL('https://example.org/foo/bar?baz');
254console.log(myURL.origin);
255// Prints https://example.org
256```
257
258```js
259const idnURL = new URL('https://測試');
260console.log(idnURL.origin);
261// Prints https://xn--g6w251d
262
263console.log(idnURL.hostname);
264// Prints xn--g6w251d
265```
266
267#### `url.password`
268
269* {string}
270
271Gets and sets the password portion of the URL.
272
273```js
274const myURL = new URL('https://abc:xyz@example.com');
275console.log(myURL.password);
276// Prints xyz
277
278myURL.password = '123';
279console.log(myURL.href);
280// Prints https://abc:123@example.com
281```
282
283Invalid URL characters included in the value assigned to the `password` property
284are [percent-encoded][]. The selection of which characters to
285percent-encode may vary somewhat from what the [`url.parse()`][] and
286[`url.format()`][] methods would produce.
287
288#### `url.pathname`
289
290* {string}
291
292Gets and sets the path portion of the URL.
293
294```js
295const myURL = new URL('https://example.org/abc/xyz?123');
296console.log(myURL.pathname);
297// Prints /abc/xyz
298
299myURL.pathname = '/abcdef';
300console.log(myURL.href);
301// Prints https://example.org/abcdef?123
302```
303
304Invalid URL characters included in the value assigned to the `pathname`
305property are [percent-encoded][]. The selection of which characters
306to percent-encode may vary somewhat from what the [`url.parse()`][] and
307[`url.format()`][] methods would produce.
308
309#### `url.port`
310
311* {string}
312
313Gets and sets the port portion of the URL.
314
315The port value may be a number or a string containing a number in the range
316`0` to `65535` (inclusive). Setting the value to the default port of the
317`URL` objects given `protocol` will result in the `port` value becoming
318the empty string (`''`).
319
320The port value can be an empty string in which case the port depends on
321the protocol/scheme:
322
323| protocol | port |
324| -------- | ---- |
325| "ftp"    | 21   |
326| "file"   |      |
327| "gopher" | 70   |
328| "http"   | 80   |
329| "https"  | 443  |
330| "ws"     | 80   |
331| "wss"    | 443  |
332
333Upon assigning a value to the port, the value will first be converted to a
334string using `.toString()`.
335
336If that string is invalid but it begins with a number, the leading number is
337assigned to `port`.
338If the number lies outside the range denoted above, it is ignored.
339
340```js
341const myURL = new URL('https://example.org:8888');
342console.log(myURL.port);
343// Prints 8888
344
345// Default ports are automatically transformed to the empty string
346// (HTTPS protocol's default port is 443)
347myURL.port = '443';
348console.log(myURL.port);
349// Prints the empty string
350console.log(myURL.href);
351// Prints https://example.org/
352
353myURL.port = 1234;
354console.log(myURL.port);
355// Prints 1234
356console.log(myURL.href);
357// Prints https://example.org:1234/
358
359// Completely invalid port strings are ignored
360myURL.port = 'abcd';
361console.log(myURL.port);
362// Prints 1234
363
364// Leading numbers are treated as a port number
365myURL.port = '5678abcd';
366console.log(myURL.port);
367// Prints 5678
368
369// Non-integers are truncated
370myURL.port = 1234.5678;
371console.log(myURL.port);
372// Prints 1234
373
374// Out-of-range numbers which are not represented in scientific notation
375// will be ignored.
376myURL.port = 1e10; // 10000000000, will be range-checked as described below
377console.log(myURL.port);
378// Prints 1234
379```
380
381Numbers which contain a decimal point,
382such as floating-point numbers or numbers in scientific notation,
383are not an exception to this rule.
384Leading numbers up to the decimal point will be set as the URL's port,
385assuming they are valid:
386
387```js
388myURL.port = 4.567e21;
389console.log(myURL.port);
390// Prints 4 (because it is the leading number in the string '4.567e21')
391```
392
393#### `url.protocol`
394
395* {string}
396
397Gets and sets the protocol portion of the URL.
398
399```js
400const myURL = new URL('https://example.org');
401console.log(myURL.protocol);
402// Prints https:
403
404myURL.protocol = 'ftp';
405console.log(myURL.href);
406// Prints ftp://example.org/
407```
408
409Invalid URL protocol values assigned to the `protocol` property are ignored.
410
411##### Special schemes
412
413The [WHATWG URL Standard][] considers a handful of URL protocol schemes to be
414_special_ in terms of how they are parsed and serialized. When a URL is
415parsed using one of these special protocols, the `url.protocol` property
416may be changed to another special protocol but cannot be changed to a
417non-special protocol, and vice versa.
418
419For instance, changing from `http` to `https` works:
420
421```js
422const u = new URL('http://example.org');
423u.protocol = 'https';
424console.log(u.href);
425// https://example.org
426```
427
428However, changing from `http` to a hypothetical `fish` protocol does not
429because the new protocol is not special.
430
431```js
432const u = new URL('http://example.org');
433u.protocol = 'fish';
434console.log(u.href);
435// http://example.org
436```
437
438Likewise, changing from a non-special protocol to a special protocol is also
439not permitted:
440
441```js
442const u = new URL('fish://example.org');
443u.protocol = 'http';
444console.log(u.href);
445// fish://example.org
446```
447
448According to the WHATWG URL Standard, special protocol schemes are `ftp`,
449`file`, `gopher`, `http`, `https`, `ws`, and `wss`.
450
451#### `url.search`
452
453* {string}
454
455Gets and sets the serialized query portion of the URL.
456
457```js
458const myURL = new URL('https://example.org/abc?123');
459console.log(myURL.search);
460// Prints ?123
461
462myURL.search = 'abc=xyz';
463console.log(myURL.href);
464// Prints https://example.org/abc?abc=xyz
465```
466
467Any invalid URL characters appearing in the value assigned the `search`
468property will be [percent-encoded][]. The selection of which
469characters to percent-encode may vary somewhat from what the [`url.parse()`][]
470and [`url.format()`][] methods would produce.
471
472#### `url.searchParams`
473
474* {URLSearchParams}
475
476Gets the [`URLSearchParams`][] object representing the query parameters of the
477URL. This property is read-only but the `URLSearchParams` object it provides
478can be used to mutate the URL instance; to replace the entirety of query
479parameters of the URL, use the [`url.search`][] setter. See
480[`URLSearchParams`][] documentation for details.
481
482Use care when using `.searchParams` to modify the `URL` because,
483per the WHATWG specification, the `URLSearchParams` object uses
484different rules to determine which characters to percent-encode. For
485instance, the `URL` object will not percent encode the ASCII tilde (`~`)
486character, while `URLSearchParams` will always encode it:
487
488```js
489const myUrl = new URL('https://example.org/abc?foo=~bar');
490
491console.log(myUrl.search);  // prints ?foo=~bar
492
493// Modify the URL via searchParams...
494myUrl.searchParams.sort();
495
496console.log(myUrl.search);  // prints ?foo=%7Ebar
497```
498
499#### `url.username`
500
501* {string}
502
503Gets and sets the username portion of the URL.
504
505```js
506const myURL = new URL('https://abc:xyz@example.com');
507console.log(myURL.username);
508// Prints abc
509
510myURL.username = '123';
511console.log(myURL.href);
512// Prints https://123:xyz@example.com/
513```
514
515Any invalid URL characters appearing in the value assigned the `username`
516property will be [percent-encoded][]. The selection of which
517characters to percent-encode may vary somewhat from what the [`url.parse()`][]
518and [`url.format()`][] methods would produce.
519
520#### `url.toString()`
521
522* Returns: {string}
523
524The `toString()` method on the `URL` object returns the serialized URL. The
525value returned is equivalent to that of [`url.href`][] and [`url.toJSON()`][].
526
527Because of the need for standard compliance, this method does not allow users
528to customize the serialization process of the URL. For more flexibility,
529[`require('url').format()`][] method might be of interest.
530
531#### `url.toJSON()`
532
533* Returns: {string}
534
535The `toJSON()` method on the `URL` object returns the serialized URL. The
536value returned is equivalent to that of [`url.href`][] and
537[`url.toString()`][].
538
539This method is automatically called when an `URL` object is serialized
540with [`JSON.stringify()`][].
541
542```js
543const myURLs = [
544  new URL('https://www.example.com'),
545  new URL('https://test.example.org')
546];
547console.log(JSON.stringify(myURLs));
548// Prints ["https://www.example.com/","https://test.example.org/"]
549```
550
551### Class: `URLSearchParams`
552<!-- YAML
553added:
554  - v7.5.0
555  - v6.13.0
556changes:
557  - version: v10.0.0
558    pr-url: https://github.com/nodejs/node/pull/18281
559    description: The class is now available on the global object.
560-->
561
562The `URLSearchParams` API provides read and write access to the query of a
563`URL`. The `URLSearchParams` class can also be used standalone with one of the
564four following constructors.
565The `URLSearchParams` class is also available on the global object.
566
567The WHATWG `URLSearchParams` interface and the [`querystring`][] module have
568similar purpose, but the purpose of the [`querystring`][] module is more
569general, as it allows the customization of delimiter characters (`&` and `=`).
570On the other hand, this API is designed purely for URL query strings.
571
572```js
573const myURL = new URL('https://example.org/?abc=123');
574console.log(myURL.searchParams.get('abc'));
575// Prints 123
576
577myURL.searchParams.append('abc', 'xyz');
578console.log(myURL.href);
579// Prints https://example.org/?abc=123&abc=xyz
580
581myURL.searchParams.delete('abc');
582myURL.searchParams.set('a', 'b');
583console.log(myURL.href);
584// Prints https://example.org/?a=b
585
586const newSearchParams = new URLSearchParams(myURL.searchParams);
587// The above is equivalent to
588// const newSearchParams = new URLSearchParams(myURL.search);
589
590newSearchParams.append('a', 'c');
591console.log(myURL.href);
592// Prints https://example.org/?a=b
593console.log(newSearchParams.toString());
594// Prints a=b&a=c
595
596// newSearchParams.toString() is implicitly called
597myURL.search = newSearchParams;
598console.log(myURL.href);
599// Prints https://example.org/?a=b&a=c
600newSearchParams.delete('a');
601console.log(myURL.href);
602// Prints https://example.org/?a=b&a=c
603```
604
605#### `new URLSearchParams()`
606
607Instantiate a new empty `URLSearchParams` object.
608
609#### `new URLSearchParams(string)`
610
611* `string` {string} A query string
612
613Parse the `string` as a query string, and use it to instantiate a new
614`URLSearchParams` object. A leading `'?'`, if present, is ignored.
615
616```js
617let params;
618
619params = new URLSearchParams('user=abc&query=xyz');
620console.log(params.get('user'));
621// Prints 'abc'
622console.log(params.toString());
623// Prints 'user=abc&query=xyz'
624
625params = new URLSearchParams('?user=abc&query=xyz');
626console.log(params.toString());
627// Prints 'user=abc&query=xyz'
628```
629
630#### `new URLSearchParams(obj)`
631<!-- YAML
632added:
633  - v7.10.0
634  - v6.13.0
635-->
636
637* `obj` {Object} An object representing a collection of key-value pairs
638
639Instantiate a new `URLSearchParams` object with a query hash map. The key and
640value of each property of `obj` are always coerced to strings.
641
642Unlike [`querystring`][] module, duplicate keys in the form of array values are
643not allowed. Arrays are stringified using [`array.toString()`][], which simply
644joins all array elements with commas.
645
646```js
647const params = new URLSearchParams({
648  user: 'abc',
649  query: ['first', 'second']
650});
651console.log(params.getAll('query'));
652// Prints [ 'first,second' ]
653console.log(params.toString());
654// Prints 'user=abc&query=first%2Csecond'
655```
656
657#### `new URLSearchParams(iterable)`
658<!-- YAML
659added:
660  - v7.10.0
661  - v6.13.0
662-->
663
664* `iterable` {Iterable} An iterable object whose elements are key-value pairs
665
666Instantiate a new `URLSearchParams` object with an iterable map in a way that
667is similar to [`Map`][]'s constructor. `iterable` can be an `Array` or any
668iterable object. That means `iterable` can be another `URLSearchParams`, in
669which case the constructor will simply create a clone of the provided
670`URLSearchParams`. Elements of `iterable` are key-value pairs, and can
671themselves be any iterable object.
672
673Duplicate keys are allowed.
674
675```js
676let params;
677
678// Using an array
679params = new URLSearchParams([
680  ['user', 'abc'],
681  ['query', 'first'],
682  ['query', 'second']
683]);
684console.log(params.toString());
685// Prints 'user=abc&query=first&query=second'
686
687// Using a Map object
688const map = new Map();
689map.set('user', 'abc');
690map.set('query', 'xyz');
691params = new URLSearchParams(map);
692console.log(params.toString());
693// Prints 'user=abc&query=xyz'
694
695// Using a generator function
696function* getQueryPairs() {
697  yield ['user', 'abc'];
698  yield ['query', 'first'];
699  yield ['query', 'second'];
700}
701params = new URLSearchParams(getQueryPairs());
702console.log(params.toString());
703// Prints 'user=abc&query=first&query=second'
704
705// Each key-value pair must have exactly two elements
706new URLSearchParams([
707  ['user', 'abc', 'error']
708]);
709// Throws TypeError [ERR_INVALID_TUPLE]:
710//        Each query pair must be an iterable [name, value] tuple
711```
712
713#### `urlSearchParams.append(name, value)`
714
715* `name` {string}
716* `value` {string}
717
718Append a new name-value pair to the query string.
719
720#### `urlSearchParams.delete(name)`
721
722* `name` {string}
723
724Remove all name-value pairs whose name is `name`.
725
726#### `urlSearchParams.entries()`
727
728* Returns: {Iterator}
729
730Returns an ES6 `Iterator` over each of the name-value pairs in the query.
731Each item of the iterator is a JavaScript `Array`. The first item of the `Array`
732is the `name`, the second item of the `Array` is the `value`.
733
734Alias for [`urlSearchParams[@@iterator]()`][`urlSearchParams@@iterator()`].
735
736#### `urlSearchParams.forEach(fn[, thisArg])`
737
738* `fn` {Function} Invoked for each name-value pair in the query
739* `thisArg` {Object} To be used as `this` value for when `fn` is called
740
741Iterates over each name-value pair in the query and invokes the given function.
742
743```js
744const myURL = new URL('https://example.org/?a=b&c=d');
745myURL.searchParams.forEach((value, name, searchParams) => {
746  console.log(name, value, myURL.searchParams === searchParams);
747});
748// Prints:
749//   a b true
750//   c d true
751```
752
753#### `urlSearchParams.get(name)`
754
755* `name` {string}
756* Returns: {string} or `null` if there is no name-value pair with the given
757  `name`.
758
759Returns the value of the first name-value pair whose name is `name`. If there
760are no such pairs, `null` is returned.
761
762#### `urlSearchParams.getAll(name)`
763
764* `name` {string}
765* Returns: {string[]}
766
767Returns the values of all name-value pairs whose name is `name`. If there are
768no such pairs, an empty array is returned.
769
770#### `urlSearchParams.has(name)`
771
772* `name` {string}
773* Returns: {boolean}
774
775Returns `true` if there is at least one name-value pair whose name is `name`.
776
777#### `urlSearchParams.keys()`
778
779* Returns: {Iterator}
780
781Returns an ES6 `Iterator` over the names of each name-value pair.
782
783```js
784const params = new URLSearchParams('foo=bar&foo=baz');
785for (const name of params.keys()) {
786  console.log(name);
787}
788// Prints:
789//   foo
790//   foo
791```
792
793#### `urlSearchParams.set(name, value)`
794
795* `name` {string}
796* `value` {string}
797
798Sets the value in the `URLSearchParams` object associated with `name` to
799`value`. If there are any pre-existing name-value pairs whose names are `name`,
800set the first such pair's value to `value` and remove all others. If not,
801append the name-value pair to the query string.
802
803```js
804const params = new URLSearchParams();
805params.append('foo', 'bar');
806params.append('foo', 'baz');
807params.append('abc', 'def');
808console.log(params.toString());
809// Prints foo=bar&foo=baz&abc=def
810
811params.set('foo', 'def');
812params.set('xyz', 'opq');
813console.log(params.toString());
814// Prints foo=def&abc=def&xyz=opq
815```
816
817#### `urlSearchParams.sort()`
818<!-- YAML
819added:
820  - v7.7.0
821  - v6.13.0
822-->
823
824Sort all existing name-value pairs in-place by their names. Sorting is done
825with a [stable sorting algorithm][], so relative order between name-value pairs
826with the same name is preserved.
827
828This method can be used, in particular, to increase cache hits.
829
830```js
831const params = new URLSearchParams('query[]=abc&type=search&query[]=123');
832params.sort();
833console.log(params.toString());
834// Prints query%5B%5D=abc&query%5B%5D=123&type=search
835```
836
837#### `urlSearchParams.toString()`
838
839* Returns: {string}
840
841Returns the search parameters serialized as a string, with characters
842percent-encoded where necessary.
843
844#### `urlSearchParams.values()`
845
846* Returns: {Iterator}
847
848Returns an ES6 `Iterator` over the values of each name-value pair.
849
850#### `urlSearchParams[Symbol.iterator]()`
851
852* Returns: {Iterator}
853
854Returns an ES6 `Iterator` over each of the name-value pairs in the query string.
855Each item of the iterator is a JavaScript `Array`. The first item of the `Array`
856is the `name`, the second item of the `Array` is the `value`.
857
858Alias for [`urlSearchParams.entries()`][].
859
860```js
861const params = new URLSearchParams('foo=bar&xyz=baz');
862for (const [name, value] of params) {
863  console.log(name, value);
864}
865// Prints:
866//   foo bar
867//   xyz baz
868```
869
870### `url.domainToASCII(domain)`
871<!-- YAML
872added:
873  - v7.4.0
874  - v6.13.0
875-->
876
877* `domain` {string}
878* Returns: {string}
879
880Returns the [Punycode][] ASCII serialization of the `domain`. If `domain` is an
881invalid domain, the empty string is returned.
882
883It performs the inverse operation to [`url.domainToUnicode()`][].
884
885```js
886const url = require('url');
887console.log(url.domainToASCII('español.com'));
888// Prints xn--espaol-zwa.com
889console.log(url.domainToASCII('中文.com'));
890// Prints xn--fiq228c.com
891console.log(url.domainToASCII('xn--iñvalid.com'));
892// Prints an empty string
893```
894
895### `url.domainToUnicode(domain)`
896<!-- YAML
897added:
898  - v7.4.0
899  - v6.13.0
900-->
901
902* `domain` {string}
903* Returns: {string}
904
905Returns the Unicode serialization of the `domain`. If `domain` is an invalid
906domain, the empty string is returned.
907
908It performs the inverse operation to [`url.domainToASCII()`][].
909
910```js
911const url = require('url');
912console.log(url.domainToUnicode('xn--espaol-zwa.com'));
913// Prints español.com
914console.log(url.domainToUnicode('xn--fiq228c.com'));
915// Prints 中文.com
916console.log(url.domainToUnicode('xn--iñvalid.com'));
917// Prints an empty string
918```
919
920### `url.fileURLToPath(url)`
921<!-- YAML
922added: v10.12.0
923-->
924
925* `url` {URL | string} The file URL string or URL object to convert to a path.
926* Returns: {string} The fully-resolved platform-specific Node.js file path.
927
928This function ensures the correct decodings of percent-encoded characters as
929well as ensuring a cross-platform valid absolute path string.
930
931```js
932new URL('file:///C:/path/').pathname;    // Incorrect: /C:/path/
933fileURLToPath('file:///C:/path/');       // Correct:   C:\path\ (Windows)
934
935new URL('file://nas/foo.txt').pathname;  // Incorrect: /foo.txt
936fileURLToPath('file://nas/foo.txt');     // Correct:   \\nas\foo.txt (Windows)
937
938new URL('file:///你好.txt').pathname;    // Incorrect: /%E4%BD%A0%E5%A5%BD.txt
939fileURLToPath('file:///你好.txt');       // Correct:   /你好.txt (POSIX)
940
941new URL('file:///hello world').pathname; // Incorrect: /hello%20world
942fileURLToPath('file:///hello world');    // Correct:   /hello world (POSIX)
943```
944
945### `url.format(URL[, options])`
946<!-- YAML
947added: v7.6.0
948-->
949
950* `URL` {URL} A [WHATWG URL][] object
951* `options` {Object}
952  * `auth` {boolean} `true` if the serialized URL string should include the
953    username and password, `false` otherwise. **Default:** `true`.
954  * `fragment` {boolean} `true` if the serialized URL string should include the
955    fragment, `false` otherwise. **Default:** `true`.
956  * `search` {boolean} `true` if the serialized URL string should include the
957    search query, `false` otherwise. **Default:** `true`.
958  * `unicode` {boolean} `true` if Unicode characters appearing in the host
959    component of the URL string should be encoded directly as opposed to being
960    Punycode encoded. **Default:** `false`.
961* Returns: {string}
962
963Returns a customizable serialization of a URL `String` representation of a
964[WHATWG URL][] object.
965
966The URL object has both a `toString()` method and `href` property that return
967string serializations of the URL. These are not, however, customizable in
968any way. The `url.format(URL[, options])` method allows for basic customization
969of the output.
970
971```js
972const myURL = new URL('https://a:b@測試?abc#foo');
973
974console.log(myURL.href);
975// Prints https://a:b@xn--g6w251d/?abc#foo
976
977console.log(myURL.toString());
978// Prints https://a:b@xn--g6w251d/?abc#foo
979
980console.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));
981// Prints 'https://測試/?abc'
982```
983
984### `url.pathToFileURL(path)`
985<!-- YAML
986added: v10.12.0
987-->
988
989* `path` {string} The path to convert to a File URL.
990* Returns: {URL} The file URL object.
991
992This function ensures that `path` is resolved absolutely, and that the URL
993control characters are correctly encoded when converting into a File URL.
994
995```js
996new URL(__filename);                // Incorrect: throws (POSIX)
997new URL(__filename);                // Incorrect: C:\... (Windows)
998pathToFileURL(__filename);          // Correct:   file:///... (POSIX)
999pathToFileURL(__filename);          // Correct:   file:///C:/... (Windows)
1000
1001new URL('/foo#1', 'file:');         // Incorrect: file:///foo#1
1002pathToFileURL('/foo#1');            // Correct:   file:///foo%231 (POSIX)
1003
1004new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c
1005pathToFileURL('/some/path%.c');    // Correct:   file:///some/path%25.c (POSIX)
1006```
1007
1008## Legacy URL API
1009<!-- YAML
1010deprecated: v11.0.0
1011-->
1012
1013### Legacy `urlObject`
1014<!-- YAML
1015changes:
1016  - version: v11.0.0
1017    pr-url: https://github.com/nodejs/node/pull/22715
1018    description: The Legacy URL API is deprecated. Use the WHATWG URL API.
1019-->
1020
1021> Stability: 0 - Deprecated: Use the WHATWG URL API instead.
1022
1023The legacy `urlObject` (`require('url').Url`) is created and returned by the
1024`url.parse()` function.
1025
1026#### `urlObject.auth`
1027
1028The `auth` property is the username and password portion of the URL, also
1029referred to as _userinfo_. This string subset follows the `protocol` and
1030double slashes (if present) and precedes the `host` component, delimited by `@`.
1031The string is either the username, or it is the username and password separated
1032by `:`.
1033
1034For example: `'user:pass'`.
1035
1036#### `urlObject.hash`
1037
1038The `hash` property is the fragment identifier portion of the URL including the
1039leading `#` character.
1040
1041For example: `'#hash'`.
1042
1043#### `urlObject.host`
1044
1045The `host` property is the full lower-cased host portion of the URL, including
1046the `port` if specified.
1047
1048For example: `'sub.example.com:8080'`.
1049
1050#### `urlObject.hostname`
1051
1052The `hostname` property is the lower-cased host name portion of the `host`
1053component *without* the `port` included.
1054
1055For example: `'sub.example.com'`.
1056
1057#### `urlObject.href`
1058
1059The `href` property is the full URL string that was parsed with both the
1060`protocol` and `host` components converted to lower-case.
1061
1062For example: `'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'`.
1063
1064#### `urlObject.path`
1065
1066The `path` property is a concatenation of the `pathname` and `search`
1067components.
1068
1069For example: `'/p/a/t/h?query=string'`.
1070
1071No decoding of the `path` is performed.
1072
1073#### `urlObject.pathname`
1074
1075The `pathname` property consists of the entire path section of the URL. This
1076is everything following the `host` (including the `port`) and before the start
1077of the `query` or `hash` components, delimited by either the ASCII question
1078mark (`?`) or hash (`#`) characters.
1079
1080For example: `'/p/a/t/h'`.
1081
1082No decoding of the path string is performed.
1083
1084#### `urlObject.port`
1085
1086The `port` property is the numeric port portion of the `host` component.
1087
1088For example: `'8080'`.
1089
1090#### `urlObject.protocol`
1091
1092The `protocol` property identifies the URL's lower-cased protocol scheme.
1093
1094For example: `'http:'`.
1095
1096#### `urlObject.query`
1097
1098The `query` property is either the query string without the leading ASCII
1099question mark (`?`), or an object returned by the [`querystring`][] module's
1100`parse()` method. Whether the `query` property is a string or object is
1101determined by the `parseQueryString` argument passed to `url.parse()`.
1102
1103For example: `'query=string'` or `{'query': 'string'}`.
1104
1105If returned as a string, no decoding of the query string is performed. If
1106returned as an object, both keys and values are decoded.
1107
1108#### `urlObject.search`
1109
1110The `search` property consists of the entire "query string" portion of the
1111URL, including the leading ASCII question mark (`?`) character.
1112
1113For example: `'?query=string'`.
1114
1115No decoding of the query string is performed.
1116
1117#### `urlObject.slashes`
1118
1119The `slashes` property is a `boolean` with a value of `true` if two ASCII
1120forward-slash characters (`/`) are required following the colon in the
1121`protocol`.
1122
1123### `url.format(urlObject)`
1124<!-- YAML
1125added: v0.1.25
1126changes:
1127  - version: v11.0.0
1128    pr-url: https://github.com/nodejs/node/pull/22715
1129    description: The Legacy URL API is deprecated. Use the WHATWG URL API.
1130  - version: v7.0.0
1131    pr-url: https://github.com/nodejs/node/pull/7234
1132    description: URLs with a `file:` scheme will now always use the correct
1133                 number of slashes regardless of `slashes` option. A falsy
1134                 `slashes` option with no protocol is now also respected at all
1135                 times.
1136-->
1137
1138> Stability: 0 - Deprecated: Use the WHATWG URL API instead.
1139
1140* `urlObject` {Object|string} A URL object (as returned by `url.parse()` or
1141  constructed otherwise). If a string, it is converted to an object by passing
1142  it to `url.parse()`.
1143
1144The `url.format()` method returns a formatted URL string derived from
1145`urlObject`.
1146
1147```js
1148url.format({
1149  protocol: 'https',
1150  hostname: 'example.com',
1151  pathname: '/some/path',
1152  query: {
1153    page: 1,
1154    format: 'json'
1155  }
1156});
1157
1158// => 'https://example.com/some/path?page=1&format=json'
1159```
1160
1161If `urlObject` is not an object or a string, `url.format()` will throw a
1162[`TypeError`][].
1163
1164The formatting process operates as follows:
1165
1166* A new empty string `result` is created.
1167* If `urlObject.protocol` is a string, it is appended as-is to `result`.
1168* Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an
1169  [`Error`][] is thrown.
1170* For all string values of `urlObject.protocol` that *do not end* with an ASCII
1171  colon (`:`) character, the literal string `:` will be appended to `result`.
1172* If either of the following conditions is true, then the literal string `//`
1173  will be appended to `result`:
1174  * `urlObject.slashes` property is true;
1175  * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or
1176    `file`;
1177* If the value of the `urlObject.auth` property is truthy, and either
1178  `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of
1179  `urlObject.auth` will be coerced into a string and appended to `result`
1180   followed by the literal string `@`.
1181* If the `urlObject.host` property is `undefined` then:
1182  * If the `urlObject.hostname` is a string, it is appended to `result`.
1183  * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string,
1184    an [`Error`][] is thrown.
1185  * If the `urlObject.port` property value is truthy, and `urlObject.hostname`
1186    is not `undefined`:
1187    * The literal string `:` is appended to `result`, and
1188    * The value of `urlObject.port` is coerced to a string and appended to
1189      `result`.
1190* Otherwise, if the `urlObject.host` property value is truthy, the value of
1191  `urlObject.host` is coerced to a string and appended to `result`.
1192* If the `urlObject.pathname` property is a string that is not an empty string:
1193  * If the `urlObject.pathname` *does not start* with an ASCII forward slash
1194    (`/`), then the literal string `'/'` is appended to `result`.
1195  * The value of `urlObject.pathname` is appended to `result`.
1196* Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an
1197  [`Error`][] is thrown.
1198* If the `urlObject.search` property is `undefined` and if the `urlObject.query`
1199  property is an `Object`, the literal string `?` is appended to `result`
1200  followed by the output of calling the [`querystring`][] module's `stringify()`
1201  method passing the value of `urlObject.query`.
1202* Otherwise, if `urlObject.search` is a string:
1203  * If the value of `urlObject.search` *does not start* with the ASCII question
1204    mark (`?`) character, the literal string `?` is appended to `result`.
1205  * The value of `urlObject.search` is appended to `result`.
1206* Otherwise, if `urlObject.search` is not `undefined` and is not a string, an
1207  [`Error`][] is thrown.
1208* If the `urlObject.hash` property is a string:
1209  * If the value of `urlObject.hash` *does not start* with the ASCII hash (`#`)
1210    character, the literal string `#` is appended to `result`.
1211  * The value of `urlObject.hash` is appended to `result`.
1212* Otherwise, if the `urlObject.hash` property is not `undefined` and is not a
1213  string, an [`Error`][] is thrown.
1214* `result` is returned.
1215
1216### `url.parse(urlString[, parseQueryString[, slashesDenoteHost]])`
1217<!-- YAML
1218added: v0.1.25
1219changes:
1220  - version: v11.14.0
1221    pr-url: https://github.com/nodejs/node/pull/26941
1222    description: The `pathname` property on the returned URL object is now `/`
1223                 when there is no path and the protocol scheme is `ws:` or
1224                 `wss:`.
1225  - version: v11.0.0
1226    pr-url: https://github.com/nodejs/node/pull/22715
1227    description: The Legacy URL API is deprecated. Use the WHATWG URL API.
1228  - version: v9.0.0
1229    pr-url: https://github.com/nodejs/node/pull/13606
1230    description: The `search` property on the returned URL object is now `null`
1231                 when no query string is present.
1232-->
1233
1234> Stability: 0 - Deprecated: Use the WHATWG URL API instead.
1235
1236* `urlString` {string} The URL string to parse.
1237* `parseQueryString` {boolean} If `true`, the `query` property will always
1238  be set to an object returned by the [`querystring`][] module's `parse()`
1239  method. If `false`, the `query` property on the returned URL object will be an
1240  unparsed, undecoded string. **Default:** `false`.
1241* `slashesDenoteHost` {boolean} If `true`, the first token after the literal
1242  string `//` and preceding the next `/` will be interpreted as the `host`.
1243  For instance, given `//foo/bar`, the result would be
1244  `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`.
1245  **Default:** `false`.
1246
1247The `url.parse()` method takes a URL string, parses it, and returns a URL
1248object.
1249
1250A `TypeError` is thrown if `urlString` is not a string.
1251
1252A `URIError` is thrown if the `auth` property is present but cannot be decoded.
1253
1254Use of the legacy `url.parse()` method is discouraged. Users should
1255use the WHATWG `URL` API. Because the `url.parse()` method uses a
1256lenient, non-standard algorithm for parsing URL strings, security
1257issues can be introduced. Specifically, issues with [host name spoofing][] and
1258incorrect handling of usernames and passwords have been identified.
1259
1260### `url.resolve(from, to)`
1261<!-- YAML
1262added: v0.1.25
1263changes:
1264  - version: v11.0.0
1265    pr-url: https://github.com/nodejs/node/pull/22715
1266    description: The Legacy URL API is deprecated. Use the WHATWG URL API.
1267  - version: v6.6.0
1268    pr-url: https://github.com/nodejs/node/pull/8215
1269    description: The `auth` fields are now kept intact when `from` and `to`
1270                 refer to the same host.
1271  - version: v6.5.0, v4.6.2
1272    pr-url: https://github.com/nodejs/node/pull/8214
1273    description: The `port` field is copied correctly now.
1274  - version: v6.0.0
1275    pr-url: https://github.com/nodejs/node/pull/1480
1276    description: The `auth` fields is cleared now the `to` parameter
1277                 contains a hostname.
1278-->
1279
1280> Stability: 0 - Deprecated: Use the WHATWG URL API instead.
1281
1282* `from` {string} The Base URL being resolved against.
1283* `to` {string} The HREF URL being resolved.
1284
1285The `url.resolve()` method resolves a target URL relative to a base URL in a
1286manner similar to that of a Web browser resolving an anchor tag HREF.
1287
1288```js
1289const url = require('url');
1290url.resolve('/one/two/three', 'four');         // '/one/two/four'
1291url.resolve('http://example.com/', '/one');    // 'http://example.com/one'
1292url.resolve('http://example.com/one', '/two'); // 'http://example.com/two'
1293```
1294
1295<a id="whatwg-percent-encoding"></a>
1296## Percent-encoding in URLs
1297
1298URLs are permitted to only contain a certain range of characters. Any character
1299falling outside of that range must be encoded. How such characters are encoded,
1300and which characters to encode depends entirely on where the character is
1301located within the structure of the URL.
1302
1303### Legacy API
1304
1305Within the Legacy API, spaces (`' '`) and the following characters will be
1306automatically escaped in the properties of URL objects:
1307
1308```text
1309< > " ` \r \n \t { } | \ ^ '
1310```
1311
1312For example, the ASCII space character (`' '`) is encoded as `%20`. The ASCII
1313forward slash (`/`) character is encoded as `%3C`.
1314
1315### WHATWG API
1316
1317The [WHATWG URL Standard][] uses a more selective and fine grained approach to
1318selecting encoded characters than that used by the Legacy API.
1319
1320The WHATWG algorithm defines four "percent-encode sets" that describe ranges
1321of characters that must be percent-encoded:
1322
1323* The *C0 control percent-encode set* includes code points in range U+0000 to
1324  U+001F (inclusive) and all code points greater than U+007E.
1325
1326* The *fragment percent-encode set* includes the *C0 control percent-encode set*
1327  and code points U+0020, U+0022, U+003C, U+003E, and U+0060.
1328
1329* The *path percent-encode set* includes the *C0 control percent-encode set*
1330  and code points U+0020, U+0022, U+0023, U+003C, U+003E, U+003F, U+0060,
1331  U+007B, and U+007D.
1332
1333* The *userinfo encode set* includes the *path percent-encode set* and code
1334  points U+002F, U+003A, U+003B, U+003D, U+0040, U+005B, U+005C, U+005D,
1335  U+005E, and U+007C.
1336
1337The *userinfo percent-encode set* is used exclusively for username and
1338passwords encoded within the URL. The *path percent-encode set* is used for the
1339path of most URLs. The *fragment percent-encode set* is used for URL fragments.
1340The *C0 control percent-encode set* is used for host and path under certain
1341specific conditions, in addition to all other cases.
1342
1343When non-ASCII characters appear within a host name, the host name is encoded
1344using the [Punycode][] algorithm. Note, however, that a host name *may* contain
1345*both* Punycode encoded and percent-encoded characters:
1346
1347```js
1348const myURL = new URL('https://%CF%80.example.com/foo');
1349console.log(myURL.href);
1350// Prints https://xn--1xa.example.com/foo
1351console.log(myURL.origin);
1352// Prints https://xn--1xa.example.com
1353```
1354
1355[`Error`]: errors.html#errors_class_error
1356[`JSON.stringify()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
1357[`Map`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
1358[`TypeError`]: errors.html#errors_class_typeerror
1359[`URLSearchParams`]: #url_class_urlsearchparams
1360[`array.toString()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString
1361[`new URL()`]: #url_new_url_input_base
1362[`querystring`]: querystring.html
1363[`require('url').format()`]: #url_url_format_url_options
1364[`url.domainToASCII()`]: #url_url_domaintoascii_domain
1365[`url.domainToUnicode()`]: #url_url_domaintounicode_domain
1366[`url.format()`]: #url_url_format_urlobject
1367[`url.href`]: #url_url_href
1368[`url.parse()`]: #url_url_parse_urlstring_parsequerystring_slashesdenotehost
1369[`url.search`]: #url_url_search
1370[`url.toJSON()`]: #url_url_tojson
1371[`url.toString()`]: #url_url_tostring
1372[`urlSearchParams.entries()`]: #url_urlsearchparams_entries
1373[`urlSearchParams@@iterator()`]: #url_urlsearchparams_symbol_iterator
1374[ICU]: intl.html#intl_options_for_building_node_js
1375[Punycode]: https://tools.ietf.org/html/rfc5891#section-4.4
1376[WHATWG URL Standard]: https://url.spec.whatwg.org/
1377[WHATWG URL]: #url_the_whatwg_url_api
1378[examples of parsed URLs]: https://url.spec.whatwg.org/#example-url-parsing
1379[host name spoofing]: https://hackerone.com/reports/678487
1380[legacy `urlObject`]: #url_legacy_urlobject
1381[percent-encoded]: #whatwg-percent-encoding
1382[stable sorting algorithm]: https://en.wikipedia.org/wiki/Sorting_algorithm#Stability
1383