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