Node.js v18.20.8 文档


网址#>

【URL】

源代码: lib/url.js

node:url 模块提供用于 URL 解析和解析的工具。可以通过以下方式访问它:

【The node:url module provides utilities for URL resolution and parsing. It can be accessed using:】

import url from 'node:url';const url = require('node:url');

URL 字符串和 URL 对象#>

【URL strings and URL objects】

URL 字符串是一个包含多个有意义组成部分的结构化字符串。解析后,将返回一个 URL 对象,其中包含每个组成部分的属性。

【A URL string is a structured string containing multiple meaningful components. When parsed, a URL object is returned containing properties for each of these components.】

node:url 模块提供了两种用于处理 URL 的 API:一种是 Node.js 特有的旧版本 API,另一种是实现了浏览器中使用的相同 WHATWG URL 标准 的新版本 API。

【The node:url module provides two APIs for working with URLs: a legacy API that is Node.js specific, and a newer API that implements the same WHATWG URL Standard used by web browsers.】

下面提供了 WHATWG 和传统 API 之间的比较。在 URL 'https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash' 上方,显示了由传统的 url.parse() 返回的对象的属性。在它下面显示的是 WHATWG URL 对象的属性。

【A comparison between the WHATWG and legacy APIs is provided below. Above the URL 'https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash', properties of an object returned by the legacy url.parse() are shown. Below it are properties of a WHATWG URL object.】

WHATWG URL 的 origin 属性包括 protocolhost,但不包括 usernamepassword

【WHATWG URL's origin property includes protocol and host, but not username or password.】

┌────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                              href                                              │
├──────────┬──┬─────────────────────┬────────────────────────┬───────────────────────────┬───────┤
│ protocol │  │        auth         │          host          │           path            │ hash  │
│          │  │                     ├─────────────────┬──────┼──────────┬────────────────┤       │
│          │  │                     │    hostname     │ port │ pathname │     search     │       │
│          │  │                     │                 │      │          ├─┬──────────────┤       │
│          │  │                     │                 │      │          │ │    query     │       │
"  https:   //    user   :   pass   @ sub.example.com : 8080   /p/a/t/h  ?  query=string   #hash "
│          │  │          │          │    hostname     │ port │          │                │       │
│          │  │          │          ├─────────────────┴──────┤          │                │       │
│ protocol │  │ username │ password │          host          │          │                │       │
├──────────┴──┼──────────┴──────────┼────────────────────────┤          │                │       │
│   origin    │                     │         origin         │ pathname │     search     │ hash  │
├─────────────┴─────────────────────┴────────────────────────┴──────────┴────────────────┴───────┤
│                                              href                                              │
└────────────────────────────────────────────────────────────────────────────────────────────────┘
(All spaces in the "" line should be ignored. They are purely for formatting.) 

使用 WHATWG API 解析网址字符串:

【Parsing the URL string using the WHATWG API:】

const myURL =
  new URL('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'); 

使用旧版 API 解析 URL 字符串:

【Parsing the URL string using the legacy API:】

import url from 'node:url';
const myURL =
  url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');const url = require('node:url');
const myURL =
  url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');

从组成部分构造 URL 并获取构造的字符串#>

【Constructing a URL from component parts and getting the constructed string】

可以使用属性设置器或模板字符串从组件部分构建 WHATWG URL:

【It is possible to construct a WHATWG URL from component parts using either the property setters or a template literal string:】

const myURL = new URL('https://example.org');
myURL.pathname = '/a/b/c';
myURL.search = '?d=e';
myURL.hash = '#fgh'; 
const pathname = '/a/b/c';
const search = '?d=e';
const hash = '#fgh';
const myURL = new URL(`https://example.org${pathname}${search}${hash}`); 

要获取构建的 URL 字符串,请使用 href 属性访问器:

【To get the constructed URL string, use the href property accessor:】

console.log(myURL.href); 

WHATWG URL API#>

【The WHATWG URL API】

类:URL#>

【Class: URL

浏览器兼容的 URL 类,按照 WHATWG URL 标准实现。解析后的 URL 示例 可在标准本身中找到。 URL 类也可以在全局对象上使用。

【Browser-compatible URL class, implemented by following the WHATWG URL Standard. Examples of parsed URLs may be found in the Standard itself. The URL class is also available on the global object.】

根据浏览器的约定,URL 对象的所有属性都作为类原型上的 getter 和 setter 实现,而不是作为对象本身的数据属性。因此,与 遗留 urlObjects 不同,对 URL 对象的任何属性使用 delete 关键字(例如 delete myURL.protocoldelete myURL.pathname 等)不会产生任何效果,但仍然会返回 true

【In accordance with browser conventions, all properties of URL objects are implemented as getters and setters on the class prototype, rather than as data properties on the object itself. Thus, unlike legacy urlObjects, using the delete keyword on any properties of URL objects (e.g. delete myURL.protocol, delete myURL.pathname, etc) has no effect but will still return true.】

new URL(input[, base])#>
  • input <string> 要解析的绝对或相对输入URL。如果 input 是相对的,则需要 base。如果 input 是绝对的,则会忽略 base。如果 input 不是字符串,则会先进行 转换为字符串
  • base <string> 如果 input 不是绝对路径,则基于该 URL 进行解析。如果 base 不是字符串,则先执行 转换为字符串

通过将 input 相对于 base 进行解析来创建一个新的 URL 对象。如果 base 以字符串形式传入,它将被解析为等同于 new URL(base)

【Creates a new URL object by parsing the input relative to the base. If base is passed as a string, it will be parsed equivalent to new URL(base).】

const myURL = new URL('/foo', 'https://example.org/');
// https://example.org/foo 

URL 构造函数可以作为全局对象上的一个属性访问。它也可以从内置的 url 模块中导入:

【The URL constructor is accessible as a property on the global object. It can also be imported from the built-in url module:】

import { URL } from 'node:url';
console.log(URL === globalThis.URL); // Prints 'true'.console.log(URL === require('node:url').URL); // Prints 'true'.

如果 inputbase 不是有效的 URL,将会抛出 TypeError。请注意,将尝试将给定的值强制转换为字符串。例如:

【A TypeError will be thrown if the input or base are not valid URLs. Note that an effort will be made to coerce the given values into strings. For instance:】

const myURL = new URL({ toString: () => 'https://example.org/' });
// https://example.org/ 

input 的主机名中出现的 Unicode 字符将自动使用 Punycode 算法转换为 ASCII。

【Unicode characters appearing within the host name of input will be automatically converted to ASCII using the Punycode algorithm.】

const myURL = new URL('https://測試');
// https://xn--g6w251d/ 

在不确定 input 是否为绝对 URL 且提供了 base 的情况下,建议验证 URL 对象的 origin 是否符合预期。

【In cases where it is not known in advance if input is an absolute URL and a base is provided, it is advised to validate that the origin of the URL object is what is expected.】

let myURL = new URL('http://Example.com/', 'https://example.org/');
// http://example.com/

myURL = new URL('https://Example.com/', 'https://example.org/');
// https://example.com/

myURL = new URL('foo://Example.com/', 'https://example.org/');
// foo://Example.com/

myURL = new URL('http:Example.com/', 'https://example.org/');
// http://example.com/

myURL = new URL('https:Example.com/', 'https://example.org/');
// https://example.org/Example.com/

myURL = new URL('foo:Example.com/', 'https://example.org/');
// foo:Example.com/ 
url.hash#>

获取和设置网址的片段部分。

【Gets and sets the fragment portion of the URL.】

const myURL = new URL('https://example.org/foo#bar');
console.log(myURL.hash);
// Prints #bar

myURL.hash = 'baz';
console.log(myURL.href);
// Prints https://example.org/foo#baz 

分配给 hash 属性的值中包含无效的 URL 字符为 百分比编码。选择要进行百分比编码的字符可能与 url.parse()url.format() 方法产生的结果略有不同。

【Invalid URL characters included in the value assigned to the hash property are percent-encoded. The selection of which characters to percent-encode may vary somewhat from what the url.parse() and url.format() methods would produce.】

url.host#>

获取和设置网址的主机部分。

【Gets and sets the host portion of the URL.】

const myURL = new URL('https://example.org:81/foo');
console.log(myURL.host);
// Prints example.org:81

myURL.host = 'example.com:82';
console.log(myURL.href);
// Prints https://example.com:82/foo 

分配给 host 属性的无效主机值将被忽略。

【Invalid host values assigned to the host property are ignored.】

url.hostname#>

获取和设置 URL 的主机名部分。url.hosturl.hostname 的关键区别在于,url.hostname 不包含端口。

【Gets and sets the host name portion of the URL. The key difference between url.host and url.hostname is that url.hostname does not include the port.】

const myURL = new URL('https://example.org:81/foo');
console.log(myURL.hostname);
// Prints example.org

// Setting the hostname does not change the port
myURL.hostname = 'example.com';
console.log(myURL.href);
// Prints https://example.com:81/foo

// Use myURL.host to change the hostname and port
myURL.host = 'example.org:82';
console.log(myURL.href);
// Prints https://example.org:82/foo 

分配给 hostname 属性的无效主机名值会被忽略。

【Invalid host name values assigned to the hostname property are ignored.】

url.href#>

获取和设置序列化的网址。

【Gets and sets the serialized URL.】

const myURL = new URL('https://example.org/foo');
console.log(myURL.href);
// Prints https://example.org/foo

myURL.href = 'https://example.com/bar';
console.log(myURL.href);
// Prints https://example.com/bar 

获取 href 属性的值等同于调用 url.toString()

【Getting the value of the href property is equivalent to calling url.toString().】

将此属性的值设置为新值等同于使用 new URL(value) 创建一个新的 URL 对象。每个 URL 对象的属性都会被修改。

【Setting the value of this property to a new value is equivalent to creating a new URL object using new URL(value). Each of the URL object's properties will be modified.】

如果赋给 href 属性的值不是有效的 URL,将会抛出 TypeError

【If the value assigned to the href property is not a valid URL, a TypeError will be thrown.】

url.origin#>

获取网址的源的只读的序列化。

【Gets the read-only serialization of the URL's origin.】

const myURL = new URL('https://example.org/foo/bar?baz');
console.log(myURL.origin);
// Prints https://example.org 
const idnURL = new URL('https://測試');
console.log(idnURL.origin);
// Prints https://xn--g6w251d

console.log(idnURL.hostname);
// Prints xn--g6w251d 
url.password#>

获取和设置网址的密码部分。

【Gets and sets the password portion of the URL.】

const myURL = new URL('https://abc:xyz@example.com');
console.log(myURL.password);
// Prints xyz

myURL.password = '123';
console.log(myURL.href);
// Prints https://abc:123@example.com/ 

password 属性中分配的值包含无效的 URL 字符是 百分比编码。需要进行百分号编码的字符选择可能与 url.parse()url.format() 方法产生的结果略有不同。

【Invalid URL characters included in the value assigned to the password property are percent-encoded. The selection of which characters to percent-encode may vary somewhat from what the url.parse() and url.format() methods would produce.】

url.pathname#>

获取和设置网址的路径部分。

【Gets and sets the path portion of the URL.】

const myURL = new URL('https://example.org/abc/xyz?123');
console.log(myURL.pathname);
// Prints /abc/xyz

myURL.pathname = '/abcdef';
console.log(myURL.href);
// Prints https://example.org/abcdef?123 

分配给 pathname 属性的值中包含无效的 URL 字符是 百分比编码。选择对哪些字符进行百分比编码可能与 url.parse()url.format() 方法产生的结果略有不同。

【Invalid URL characters included in the value assigned to the pathname property are percent-encoded. The selection of which characters to percent-encode may vary somewhat from what the url.parse() and url.format() methods would produce.】

url.port#>

获取和设置网址的端口部分。

【Gets and sets the port portion of the URL.】

端口值可以是一个数字,也可以是一个包含数字的字符串,范围在 065535(含)之间。将该值设置为给定 protocolURL 对象的默认端口,将导致 port 值变为空字符串('')。

【The port value may be a number or a string containing a number in the range 0 to 65535 (inclusive). Setting the value to the default port of the URL objects given protocol will result in the port value becoming the empty string ('').】

端口值可以是空字符串,此时端口取决于协议/方案:

【The port value can be an empty string in which case the port depends on the protocol/scheme:】

协议端口
"ftp"21
"file"
"http"80
"https"443
"ws"80
"wss"443

在给端口赋值时,该值将首先使用 .toString() 转换为字符串。

【Upon assigning a value to the port, the value will first be converted to a string using .toString().】

如果该字符串无效但以数字开头,则开头的数字会被赋值给 port。如果该数字超出上述范围,则会被忽略。

【If that string is invalid but it begins with a number, the leading number is assigned to port. If the number lies outside the range denoted above, it is ignored.】

const myURL = new URL('https://example.org:8888');
console.log(myURL.port);
// Prints 8888

// Default ports are automatically transformed to the empty string
// (HTTPS protocol's default port is 443)
myURL.port = '443';
console.log(myURL.port);
// Prints the empty string
console.log(myURL.href);
// Prints https://example.org/

myURL.port = 1234;
console.log(myURL.port);
// Prints 1234
console.log(myURL.href);
// Prints https://example.org:1234/

// Completely invalid port strings are ignored
myURL.port = 'abcd';
console.log(myURL.port);
// Prints 1234

// Leading numbers are treated as a port number
myURL.port = '5678abcd';
console.log(myURL.port);
// Prints 5678

// Non-integers are truncated
myURL.port = 1234.5678;
console.log(myURL.port);
// Prints 1234

// Out-of-range numbers which are not represented in scientific notation
// will be ignored.
myURL.port = 1e10; // 10000000000, will be range-checked as described below
console.log(myURL.port);
// Prints 1234 

包含小数点的数字,如浮点数或科学记数法表示的数字,也不例外。小数点前的前导数字将被设置为 URL 的端口,前提是它们有效:

【Numbers which contain a decimal point, such as floating-point numbers or numbers in scientific notation, are not an exception to this rule. Leading numbers up to the decimal point will be set as the URL's port, assuming they are valid:】

myURL.port = 4.567e21;
console.log(myURL.port);
// Prints 4 (because it is the leading number in the string '4.567e21') 
url.protocol#>

获取和设置网址的协议部分。

【Gets and sets the protocol portion of the URL.】

const myURL = new URL('https://example.org');
console.log(myURL.protocol);
// Prints https:

myURL.protocol = 'ftp';
console.log(myURL.href);
// Prints ftp://example.org/ 

分配给 protocol 属性的无效 URL 协议值将被忽略。

【Invalid URL protocol values assigned to the protocol property are ignored.】

特别计划#>

【Special schemes】

WHATWG URL 标准 将少数几种 URL 协议方案视为在解析和序列化方面具有特殊性的协议。当使用这些特殊协议之一解析 URL 时,url.protocol 属性可能会被更改为另一种特殊协议,但不能更改为非特殊协议,反之亦然。

【The WHATWG URL Standard considers a handful of URL protocol schemes to be special in terms of how they are parsed and serialized. When a URL is parsed using one of these special protocols, the url.protocol property may be changed to another special protocol but cannot be changed to a non-special protocol, and vice versa.】

例如,将 http 改为 https 是可行的:

【For instance, changing from http to https works:】

const u = new URL('http://example.org');
u.protocol = 'https';
console.log(u.href);
// https://example.org/ 

然而,从 http 改为假想的 fish 协议并不会有什么不同,因为这个新协议并不特殊。

【However, changing from http to a hypothetical fish protocol does not because the new protocol is not special.】

const u = new URL('http://example.org');
u.protocol = 'fish';
console.log(u.href);
// http://example.org/ 

同样地,从非专用协议更改为专用协议也是不允许的:

【Likewise, changing from a non-special protocol to a special protocol is also not permitted:】

const u = new URL('fish://example.org');
u.protocol = 'http';
console.log(u.href);
// fish://example.org 

根据 WHATWG URL 标准,特殊协议方案包括 ftpfilehttphttpswswss

【According to the WHATWG URL Standard, special protocol schemes are ftp, file, http, https, ws, and wss.】

url.search#>

获取和设置网址的序列化的查询部分。

【Gets and sets the serialized query portion of the URL.】

const myURL = new URL('https://example.org/abc?123');
console.log(myURL.search);
// Prints ?123

myURL.search = 'abc=xyz';
console.log(myURL.href);
// Prints https://example.org/abc?abc=xyz 

在分配给 search 属性的值中出现的任何无效 URL 字符都将被 百分比编码 编码。哪些字符需要进行百分比编码的选择,可能会与 url.parse()url.format() 方法生成的结果略有不同。

【Any invalid URL characters appearing in the value assigned the search property will be percent-encoded. The selection of which characters to percent-encode may vary somewhat from what the url.parse() and url.format() methods would produce.】

url.searchParams#>

获取表示 URL 查询参数的 URLSearchParams 对象。此属性是只读的,但它提供的 URLSearchParams 对象可以用来修改 URL 实例;要替换 URL 的所有查询参数,请使用 url.search 设置器。详情请参阅 URLSearchParams 文档。

【Gets the URLSearchParams object representing the query parameters of the URL. This property is read-only but the URLSearchParams object it provides can be used to mutate the URL instance; to replace the entirety of query parameters of the URL, use the url.search setter. See URLSearchParams documentation for details.】

在使用 .searchParams 修改 URL 时要小心,因为根据 WHATWG 规范,URLSearchParams 对象使用不同的规则来确定哪些字符需要进行百分比编码。例如,URL 对象不会对 ASCII 波浪号 (~) 字符进行百分比编码,而 URLSearchParams 总是会对其进行编码:

【Use care when using .searchParams to modify the URL because, per the WHATWG specification, the URLSearchParams object uses different rules to determine which characters to percent-encode. For instance, the URL object will not percent encode the ASCII tilde (~) character, while URLSearchParams will always encode it:】

const myURL = new URL('https://example.org/abc?foo=~bar');

console.log(myURL.search);  // prints ?foo=~bar

// Modify the URL via searchParams...
myURL.searchParams.sort();

console.log(myURL.search);  // prints ?foo=%7Ebar 
url.username#>

获取和设置网址的用户名部分。

【Gets and sets the username portion of the URL.】

const myURL = new URL('https://abc:xyz@example.com');
console.log(myURL.username);
// Prints abc

myURL.username = '123';
console.log(myURL.href);
// Prints https://123:xyz@example.com/ 

分配给 username 属性的值中出现的任何无效 URL 字符将被 百分比编码。选择要进行百分比编码的字符可能与 url.parse()url.format() 方法产生的结果略有不同。

【Any invalid URL characters appearing in the value assigned the username property will be percent-encoded. The selection of which characters to percent-encode may vary somewhat from what the url.parse() and url.format() methods would produce.】

url.toString()#>

URL 对象的 toString() 方法返回序列化后的 URL。返回的值等同于 url.hrefurl.toJSON() 的值。

【The toString() method on the URL object returns the serialized URL. The value returned is equivalent to that of url.href and url.toJSON().】

url.toJSON()#>

URL 对象上的 toJSON() 方法返回序列化的 URL。返回的值等同于 url.hrefurl.toString() 的值。

【The toJSON() method on the URL object returns the serialized URL. The value returned is equivalent to that of url.href and url.toString().】

URL 对象使用 JSON.stringify() 序列化时,会自动调用此方法。

【This method is automatically called when an URL object is serialized with JSON.stringify().】

const myURLs = [
  new URL('https://www.example.com'),
  new URL('https://test.example.org'),
];
console.log(JSON.stringify(myURLs));
// Prints ["https://www.example.com/","https://test.example.org/"] 
URL.createObjectURL(blob)#>

稳定性: 1 - 实验性

创建一个 'blob:nodedata:...' URL 字符串,该字符串表示给定的 <Blob> 对象,并可用于稍后检索 Blob

【Creates a 'blob:nodedata:...' URL string that represents the given <Blob> object and can be used to retrieve the Blob later.】

const {
  Blob,
  resolveObjectURL,
} = require('node:buffer');

const blob = new Blob(['hello']);
const id = URL.createObjectURL(blob);

// later...

const otherBlob = resolveObjectURL(id);
console.log(otherBlob.size); 

已注册的 <Blob> 存储的数据将保留在内存中,直到调用 URL.revokeObjectURL() 将其移除为止。

【The data stored by the registered <Blob> will be retained in memory until URL.revokeObjectURL() is called to remove it.】

Blob 对象在当前线程中注册。如果使用 Worker 线程,在一个 Worker 中注册的 Blob 对象将无法在其他 Worker 或主线程中使用。

URL.revokeObjectURL(id)#>

稳定性: 1 - 实验性

  • id <string> 由先前调用 URL.createObjectURL() 返回的 'blob:nodedata:... URL 字符串。

移除由给定 ID 标识的存储 <Blob>。尝试撤销未注册的 ID 将默默失败。

【Removes the stored <Blob> identified by the given ID. Attempting to revoke a ID that isn't registered will silently fail.】

URL.canParse(input[, base])#>
  • input <string> 要解析的绝对或相对输入URL。如果 input 是相对的,则需要 base。如果 input 是绝对的,则会忽略 base。如果 input 不是字符串,则会先进行 转换为字符串
  • base <string> 如果 input 不是绝对路径,则基于该 URL 进行解析。如果 base 不是字符串,则先执行 转换为字符串
  • 返回:<boolean>

检查相对于 baseinput 是否可以解析为 URL

【Checks if an input relative to the base can be parsed to a URL.】

const isValid = URL.canParse('/foo', 'https://example.org/'); // true

const isNotValid = URL.canParse('/foo'); // false 

类:URLSearchParams#>

【Class: URLSearchParams

URLSearchParams API 提供对 URL 查询部分的读写访问。URLSearchParams 类也可以独立使用,支持以下四种构造函数之一。URLSearchParams 类也可以在全局对象上使用。

【The URLSearchParams API provides read and write access to the query of a URL. The URLSearchParams class can also be used standalone with one of the four following constructors. The URLSearchParams class is also available on the global object.】

WHATWG 的 URLSearchParams 接口和 querystring 模块有类似的用途,但 querystring 模块的用途更广泛,因为它允许自定义分隔符字符(&=)。另一方面,这个 API 是专为 URL 查询字符串而设计的。

【The WHATWG URLSearchParams interface and the querystring module have similar purpose, but the purpose of the querystring module is more general, as it allows the customization of delimiter characters (& and =). On the other hand, this API is designed purely for URL query strings.】

const myURL = new URL('https://example.org/?abc=123');
console.log(myURL.searchParams.get('abc'));
// Prints 123

myURL.searchParams.append('abc', 'xyz');
console.log(myURL.href);
// Prints https://example.org/?abc=123&abc=xyz

myURL.searchParams.delete('abc');
myURL.searchParams.set('a', 'b');
console.log(myURL.href);
// Prints https://example.org/?a=b

const newSearchParams = new URLSearchParams(myURL.searchParams);
// The above is equivalent to
// const newSearchParams = new URLSearchParams(myURL.search);

newSearchParams.append('a', 'c');
console.log(myURL.href);
// Prints https://example.org/?a=b
console.log(newSearchParams.toString());
// Prints a=b&a=c

// newSearchParams.toString() is implicitly called
myURL.search = newSearchParams;
console.log(myURL.href);
// Prints https://example.org/?a=b&a=c
newSearchParams.delete('a');
console.log(myURL.href);
// Prints https://example.org/?a=b&a=c 
new URLSearchParams()#>

实例化一个新的空 URLSearchParams 对象。

【Instantiate a new empty URLSearchParams object.】

new URLSearchParams(string)#>

string 解析为查询字符串,并使用它来实例化一个新的 URLSearchParams 对象。如果存在前导的 '?',将会被忽略。

【Parse the string as a query string, and use it to instantiate a new URLSearchParams object. A leading '?', if present, is ignored.】

let params;

params = new URLSearchParams('user=abc&query=xyz');
console.log(params.get('user'));
// Prints 'abc'
console.log(params.toString());
// Prints 'user=abc&query=xyz'

params = new URLSearchParams('?user=abc&query=xyz');
console.log(params.toString());
// Prints 'user=abc&query=xyz' 
new URLSearchParams(obj)#>
  • obj <Object> 表示一组键值对的对象

使用查询哈希映射实例化一个新的 URLSearchParams 对象。obj 的每个属性的键和值总是被强制转换为字符串。

【Instantiate a new URLSearchParams object with a query hash map. The key and value of each property of obj are always coerced to strings.】

querystring 模块不同,表单中不允许出现作为数组值的重复键。数组使用 array.toString() 转换为字符串,方法是将所有数组元素用逗号连接。

【Unlike querystring module, duplicate keys in the form of array values are not allowed. Arrays are stringified using array.toString(), which simply joins all array elements with commas.】

const params = new URLSearchParams({
  user: 'abc',
  query: ['first', 'second'],
});
console.log(params.getAll('query'));
// Prints [ 'first,second' ]
console.log(params.toString());
// Prints 'user=abc&query=first%2Csecond' 
new URLSearchParams(iterable)#>
  • iterable <Iterable> 一个其元素为键值对的可迭代对象

使用可迭代的映射实例化一个新的 URLSearchParams 对象,其方式类似于 Map 的构造函数。iterable 可以是一个 Array 或任何可迭代对象。这意味着 iterable 可以是另一个 URLSearchParams,在这种情况下,构造函数将简单地创建所提供 URLSearchParams 的克隆。iterable 的元素是键值对,并且它们本身可以是任何可迭代对象。

【Instantiate a new URLSearchParams object with an iterable map in a way that is similar to Map's constructor. iterable can be an Array or any iterable object. That means iterable can be another URLSearchParams, in which case the constructor will simply create a clone of the provided URLSearchParams. Elements of iterable are key-value pairs, and can themselves be any iterable object.】

允许重复的键。

【Duplicate keys are allowed.】

let params;

// Using an array
params = new URLSearchParams([
  ['user', 'abc'],
  ['query', 'first'],
  ['query', 'second'],
]);
console.log(params.toString());
// Prints 'user=abc&query=first&query=second'

// Using a Map object
const map = new Map();
map.set('user', 'abc');
map.set('query', 'xyz');
params = new URLSearchParams(map);
console.log(params.toString());
// Prints 'user=abc&query=xyz'

// Using a generator function
function* getQueryPairs() {
  yield ['user', 'abc'];
  yield ['query', 'first'];
  yield ['query', 'second'];
}
params = new URLSearchParams(getQueryPairs());
console.log(params.toString());
// Prints 'user=abc&query=first&query=second'

// Each key-value pair must have exactly two elements
new URLSearchParams([
  ['user', 'abc', 'error'],
]);
// Throws TypeError [ERR_INVALID_TUPLE]:
//        Each query pair must be an iterable [name, value] tuple 
urlSearchParams.append(name, value)#>

将新的名称-值对追加到查询字符串。

【Append a new name-value pair to the query string.】

urlSearchParams.delete(name[, value])#>

如果提供了 value,则删除所有名称为 name 且值为 value 的名值对。

【If value is provided, removes all name-value pairs where name is name and value is value..】

如果未提供 value,则会删除所有名称为 name 的名称-值对。

【If value is not provided, removes all name-value pairs whose name is name.】

urlSearchParams.entries()#>

返回一个 ES6 Iterator,用于迭代查询中的每个名称-值对。迭代器的每一项都是一个 JavaScript ArrayArray 的第一项是 name,第二项是 value

【Returns an ES6 Iterator over each of the name-value pairs in the query. Each item of the iterator is a JavaScript Array. The first item of the Array is the name, the second item of the Array is the value.】

urlSearchParams[@@iterator]() 的别名。

【Alias for urlSearchParams[@@iterator]().】

urlSearchParams.forEach(fn[, thisArg])#>
  • fn <Function> 对查询中的每个名称-值对调用
  • thisArg <Object> 在调用 fn 时用作 this 的值

迭代查询中的每个名称-值对并调用给定的函数。

【Iterates over each name-value pair in the query and invokes the given function.】

const myURL = new URL('https://example.org/?a=b&c=d');
myURL.searchParams.forEach((value, name, searchParams) => {
  console.log(name, value, myURL.searchParams === searchParams);
});
// Prints:
//   a b true
//   c d true 
urlSearchParams.get(name)#>
  • name <string>
  • 返回:<string>,如果没有与给定 name 对应的名称-值对,则返回 null

返回名称为 name 的第一个名称-值对的值。如果没有这样的对,则返回 null

【Returns the value of the first name-value pair whose name is name. If there are no such pairs, null is returned.】

urlSearchParams.getAll(name)#>

返回所有名称为 name 的名称-值对的值。如果没有这样的对,则返回一个空数组。

【Returns the values of all name-value pairs whose name is name. If there are no such pairs, an empty array is returned.】

urlSearchParams.has(name[, value])#>

检查 URLSearchParams 对象是否包含基于 name 以及可选 value 参数的键值对。

【Checks if the URLSearchParams object contains key-value pair(s) based on name and an optional value argument.】

如果提供了 value,当存在相同 namevalue 的名称-值对时返回 true

【If value is provided, returns true when name-value pair with same name and value exists.】

如果未提供 value,则当至少存在一个名称为 name 的名值对时返回 true

【If value is not provided, returns true if there is at least one name-value pair whose name is name.】

urlSearchParams.keys()#>

返回一个 ES6 Iterator,用于遍历每个名称-值对的名称。

【Returns an ES6 Iterator over the names of each name-value pair.】

const params = new URLSearchParams('foo=bar&foo=baz');
for (const name of params.keys()) {
  console.log(name);
}
// Prints:
//   foo
//   foo 
urlSearchParams.set(name, value)#>

将与 name 关联的 URLSearchParams 对象中的值设置为 value。如果存在任何预先存在的名称为 name 的键值对,则将第一个此类键值对的值设置为 value,并删除其他所有键值对。如果不存在,则将该名称-值对附加到查询字符串中。

【Sets the value in the URLSearchParams object associated with name to value. If there are any pre-existing name-value pairs whose names are name, set the first such pair's value to value and remove all others. If not, append the name-value pair to the query string.】

const params = new URLSearchParams();
params.append('foo', 'bar');
params.append('foo', 'baz');
params.append('abc', 'def');
console.log(params.toString());
// Prints foo=bar&foo=baz&abc=def

params.set('foo', 'def');
params.set('xyz', 'opq');
console.log(params.toString());
// Prints foo=def&abc=def&xyz=opq 
urlSearchParams.size#>

参数条目的总数。

【The total number of parameter entries.】

urlSearchParams.sort()#>

按名称就地对所有现有的名称-值对进行排序。排序是用 稳定排序算法 进行的,因此具有相同名称的名称-值对之间的相对顺序会被保留。

【Sort all existing name-value pairs in-place by their names. Sorting is done with a stable sorting algorithm, so relative order between name-value pairs with the same name is preserved.】

该方法尤其可用于增加缓存命中。

【This method can be used, in particular, to increase cache hits.】

const params = new URLSearchParams('query[]=abc&type=search&query[]=123');
params.sort();
console.log(params.toString());
// Prints query%5B%5D=abc&query%5B%5D=123&type=search 
urlSearchParams.toString()#>

返回序列化为字符串的搜索参数,在必要时对字符进行百分号编码。

【Returns the search parameters serialized as a string, with characters percent-encoded where necessary.】

urlSearchParams.values()#>

返回一个 ES6 Iterator,用于遍历每个名称-值对的值。

【Returns an ES6 Iterator over the values of each name-value pair.】

urlSearchParams[Symbol.iterator]()#>

返回一个 ES6 Iterator,用于遍历查询字符串中的每个名称-值对。迭代器的每一项都是一个 JavaScript ArrayArray 的第一个元素是 name,第二个元素是 value

【Returns an ES6 Iterator over each of the name-value pairs in the query string. Each item of the iterator is a JavaScript Array. The first item of the Array is the name, the second item of the Array is the value.】

urlSearchParams.entries() 的别名。

【Alias for urlSearchParams.entries().】

const params = new URLSearchParams('foo=bar&xyz=baz');
for (const [name, value] of params) {
  console.log(name, value);
}
// Prints:
//   foo bar
//   xyz baz 

url.domainToASCII(domain)#>

返回 domainPunycode ASCII 序列化。如果 domain 是无效域名,则返回空字符串。

【Returns the Punycode ASCII serialization of the domain. If domain is an invalid domain, the empty string is returned.】

它执行与 url.domainToUnicode() 相反的操作。

【It performs the inverse operation to url.domainToUnicode().】

import url from 'node:url';

console.log(url.domainToASCII('español.com'));
// Prints xn--espaol-zwa.com
console.log(url.domainToASCII('中文.com'));
// Prints xn--fiq228c.com
console.log(url.domainToASCII('xn--iñvalid.com'));
// Prints an empty stringconst url = require('node:url');

console.log(url.domainToASCII('español.com'));
// Prints xn--espaol-zwa.com
console.log(url.domainToASCII('中文.com'));
// Prints xn--fiq228c.com
console.log(url.domainToASCII('xn--iñvalid.com'));
// Prints an empty string

url.domainToUnicode(domain)#>

返回 domain 的 Unicode 序列化。如果 domain 是无效的域名,则返回空字符串。

【Returns the Unicode serialization of the domain. If domain is an invalid domain, the empty string is returned.】

它执行与 url.domainToASCII() 相反的操作。

【It performs the inverse operation to url.domainToASCII().】

import url from 'node:url';

console.log(url.domainToUnicode('xn--espaol-zwa.com'));
// Prints español.com
console.log(url.domainToUnicode('xn--fiq228c.com'));
// Prints 中文.com
console.log(url.domainToUnicode('xn--iñvalid.com'));
// Prints an empty stringconst url = require('node:url');

console.log(url.domainToUnicode('xn--espaol-zwa.com'));
// Prints español.com
console.log(url.domainToUnicode('xn--fiq228c.com'));
// Prints 中文.com
console.log(url.domainToUnicode('xn--iñvalid.com'));
// Prints an empty string

url.fileURLToPath(url)#>

  • url <URL> | <string> 要转换为路径的文件 URL 字符串或 URL 对象。
  • 返回:<string> 完全解析的特定平台的 Node.js 文件路径。

此函数确保对百分号编码字符的正确解码,同时确保生成跨平台有效的绝对路径字符串。

【This function ensures the correct decodings of percent-encoded characters as well as ensuring a cross-platform valid absolute path string.】

import { fileURLToPath } from 'node:url';

const __filename = fileURLToPath(import.meta.url);

new URL('file:///C:/path/').pathname;      // Incorrect: /C:/path/
fileURLToPath('file:///C:/path/');         // Correct:   C:\path\ (Windows)

new URL('file://nas/foo.txt').pathname;    // Incorrect: /foo.txt
fileURLToPath('file://nas/foo.txt');       // Correct:   \\nas\foo.txt (Windows)

new URL('file:///你好.txt').pathname;      // Incorrect: /%E4%BD%A0%E5%A5%BD.txt
fileURLToPath('file:///你好.txt');         // Correct:   /你好.txt (POSIX)

new URL('file:///hello world').pathname;   // Incorrect: /hello%20world
fileURLToPath('file:///hello world');      // Correct:   /hello world (POSIX)const { fileURLToPath } = require('node:url');
new URL('file:///C:/path/').pathname;      // Incorrect: /C:/path/
fileURLToPath('file:///C:/path/');         // Correct:   C:\path\ (Windows)

new URL('file://nas/foo.txt').pathname;    // Incorrect: /foo.txt
fileURLToPath('file://nas/foo.txt');       // Correct:   \\nas\foo.txt (Windows)

new URL('file:///你好.txt').pathname;      // Incorrect: /%E4%BD%A0%E5%A5%BD.txt
fileURLToPath('file:///你好.txt');         // Correct:   /你好.txt (POSIX)

new URL('file:///hello world').pathname;   // Incorrect: /hello%20world
fileURLToPath('file:///hello world');      // Correct:   /hello world (POSIX)

url.format(URL[, options])#>

  • URL <URL> 一个 WHATWG URL 对象
  • options <Object>
    • auth <boolean> 如果序列化后的 URL 字符串应包含用户名和密码,则为 true,否则为 false默认值: true
    • fragment <boolean> 如果序列化的 URL 字符串应包含片段,则为 true,否则为 false默认值: true
    • search <boolean> 如果序列化的 URL 字符串应包含搜索查询,则为 true,否则为 false默认值: true
    • unicode <boolean> 如果 URL 字符串的主机部分中出现的 Unicode 字符应直接编码而不是使用 Punycode 编码,则为 true默认值: false
  • 返回:<string>

返回 WHATWG URL 对象的 URL String 表示的可自定义序列化。

【Returns a customizable serialization of a URL String representation of a WHATWG URL object.】

URL 对象既有返回 URL 字符串序列的 toString() 方法,也有 href 属性。然而,它们都无法进行任何自定义。url.format(URL[, options]) 方法则允许对输出进行基本的自定义。

【The URL object has both a toString() method and href property that return string serializations of the URL. These are not, however, customizable in any way. The url.format(URL[, options]) method allows for basic customization of the output.】

import url from 'node:url';
const myURL = new URL('https://a:b@測試?abc#foo');

console.log(myURL.href);
// Prints https://a:b@xn--g6w251d/?abc#foo

console.log(myURL.toString());
// Prints https://a:b@xn--g6w251d/?abc#foo

console.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));
// Prints 'https://測試/?abc'const url = require('node:url');
const myURL = new URL('https://a:b@測試?abc#foo');

console.log(myURL.href);
// Prints https://a:b@xn--g6w251d/?abc#foo

console.log(myURL.toString());
// Prints https://a:b@xn--g6w251d/?abc#foo

console.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));
// Prints 'https://測試/?abc'

url.pathToFileURL(path)#>

  • path <string> 要转换为文件 URL 的路径。
  • 返回:<URL> 文件的 URL 对象。

此函数确保 path 被绝对解析,并且在转换为文件 URL 时 URL 控制字符被正确编码。

【This function ensures that path is resolved absolutely, and that the URL control characters are correctly encoded when converting into a File URL.】

import { pathToFileURL } from 'node:url';

new URL('/foo#1', 'file:');           // Incorrect: file:///foo#1
pathToFileURL('/foo#1');              // Correct:   file:///foo%231 (POSIX)

new URL('/some/path%.c', 'file:');    // Incorrect: file:///some/path%.c
pathToFileURL('/some/path%.c');       // Correct:   file:///some/path%25.c (POSIX)const { pathToFileURL } = require('node:url');
new URL(__filename);                  // Incorrect: throws (POSIX)
new URL(__filename);                  // Incorrect: C:\... (Windows)
pathToFileURL(__filename);            // Correct:   file:///... (POSIX)
pathToFileURL(__filename);            // Correct:   file:///C:/... (Windows)

new URL('/foo#1', 'file:');           // Incorrect: file:///foo#1
pathToFileURL('/foo#1');              // Correct:   file:///foo%231 (POSIX)

new URL('/some/path%.c', 'file:');    // Incorrect: file:///some/path%.c
pathToFileURL('/some/path%.c');       // Correct:   file:///some/path%25.c (POSIX)

url.urlToHttpOptions(url)#>

  • url <URL> 要转换为选项对象的 WHATWG URL 对象。
  • 返回:<Object> 选项对象
    • protocol <string> 要使用的协议。
    • hostname <string> 发出请求的服务器的域名或IP地址。
    • hash <string> URL 的片段部分。
    • search <string> URL 的序列化查询部分。
    • pathname <string> URL 的路径部分。
    • path <string> 请求路径。如果有查询字符串,应一并包括。例如:'/index.html?page=12'。当请求路径包含非法字符时,会抛出异常。目前仅拒绝空格,但将来可能会有所变化。
    • href <string> 序列化的 URL。
    • port <number> 远程服务器端口。
    • auth <string> 基本身份验证,即 'user:password' 用于计算 Authorization 头。

此实用函数将 URL 对象转换为普通的选项对象,以符合 http.request()https.request() API 的预期。

【This utility function converts a URL object into an ordinary options object as expected by the http.request() and https.request() APIs.】

import { urlToHttpOptions } from 'node:url';
const myURL = new URL('https://a:b@測試?abc#foo');

console.log(urlToHttpOptions(myURL));
/*
{
  protocol: 'https:',
  hostname: 'xn--g6w251d',
  hash: '#foo',
  search: '?abc',
  pathname: '/',
  path: '/?abc',
  href: 'https://a:b@xn--g6w251d/?abc#foo',
  auth: 'a:b'
}
*/const { urlToHttpOptions } = require('node:url');
const myURL = new URL('https://a:b@測試?abc#foo');

console.log(urlToHttpOptions(myURL));
/*
{
  protocol: 'https:',
  hostname: 'xn--g6w251d',
  hash: '#foo',
  search: '?abc',
  pathname: '/',
  path: '/?abc',
  href: 'https://a:b@xn--g6w251d/?abc#foo',
  auth: 'a:b'
}
*/

旧版 URL API#>

【Legacy URL API】

稳定性: 3 - 传统做法:请改用 WHATWG URL API。

遗留 urlObject#>

【Legacy urlObject

稳定性: 3 - 传统做法:请改用 WHATWG URL API。

传统的 urlObjectrequire('node:url').Urlimport { Url } from 'node:url')是由 url.parse() 函数创建并返回的。

【The legacy urlObject (require('node:url').Url or import { Url } from 'node:url') is created and returned by the url.parse() function.】

urlObject.auth#>

auth 属性是 URL 中的用户名和密码部分,也称为 userinfo。这个字符串子集位于 protocol 和双斜杠(如果存在)之后,并在 host 组件之前,用 @ 分隔。这个字符串要么只是用户名,要么是用户名和密码,用 : 分隔。

【The auth property is the username and password portion of the URL, also referred to as userinfo. This string subset follows the protocol and double slashes (if present) and precedes the host component, delimited by @. The string is either the username, or it is the username and password separated by :.】

例如:'user:pass'

【For example: 'user:pass'.】

urlObject.hash#>

hash 属性是 URL 的片段标识符部分,包括前导的 # 字符。

【The hash property is the fragment identifier portion of the URL including the leading # character.】

例如:'#hash'

【For example: '#hash'.】

urlObject.host#>

host 属性是 URL 的完整小写主机部分,包括指定的 port(端口)。

【The host property is the full lower-cased host portion of the URL, including the port if specified.】

例如:'sub.example.com:8080'

【For example: 'sub.example.com:8080'.】

urlObject.hostname#>

hostname 属性是 host 组件中不包含 port 的小写主机名部分。

【The hostname property is the lower-cased host name portion of the host component without the port included.】

例如:'sub.example.com'

【For example: 'sub.example.com'.】

urlObject.href#>

href 属性是完整的 URL 字符串,解析时将 protocolhost 组件都转换为小写。

【The href property is the full URL string that was parsed with both the protocol and host components converted to lower-case.】

例如:'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'

【For example: 'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'.】

urlObject.path#>

path 属性是 pathnamesearch 组件的拼接。

【The path property is a concatenation of the pathname and search components.】

例如:'/p/a/t/h?query=string'

【For example: '/p/a/t/h?query=string'.】

不会对 path 进行解码。

【No decoding of the path is performed.】

urlObject.pathname#>

pathname 属性由 URL 的整个路径部分组成。它包含了紧随 host(包括 port)之后,到 queryhash 组件开始之前的所有内容,由 ASCII 问号(?)或井号(#)字符分隔。

【The pathname property consists of the entire path section of the URL. This is everything following the host (including the port) and before the start of the query or hash components, delimited by either the ASCII question mark (?) or hash (#) characters.】

例如:'/p/a/t/h'

【For example: '/p/a/t/h'.】

不执行路径字符串的解码。

【No decoding of the path string is performed.】

urlObject.port#>

port 属性是 host 组件中的数字端口部分。

【The port property is the numeric port portion of the host component.】

例如:'8080'

【For example: '8080'.】

urlObject.protocol#>

protocol 属性用于标识 URL 的小写协议方案。

【The protocol property identifies the URL's lower-cased protocol scheme.】

例如:'http:'

【For example: 'http:'.】

urlObject.query#>

query 属性可以是没有前导 ASCII 问号 (?) 的查询字符串,或者是由 querystring 模块的 parse() 方法返回的对象。query 属性是字符串还是对象取决于传递给 url.parse()parseQueryString 参数。

【The query property is either the query string without the leading ASCII question mark (?), or an object returned by the querystring module's parse() method. Whether the query property is a string or object is determined by the parseQueryString argument passed to url.parse().】

例如:'query=string'{'query': 'string'}

【For example: 'query=string' or {'query': 'string'}.】

如果作为字符串返回,则不会对查询字符串进行解码。如果作为对象返回,则键和值都会被解码。

【If returned as a string, no decoding of the query string is performed. If returned as an object, both keys and values are decoded.】

urlObject.search#>

search 属性包括 URL 的整个“查询字符串”部分,包括开头的 ASCII 问号 (?) 字符。

【The search property consists of the entire "query string" portion of the URL, including the leading ASCII question mark (?) character.】

例如:'?query=string'

【For example: '?query=string'.】

不执行查询字符串的解码。

【No decoding of the query string is performed.】

urlObject.slashes#>

slashes 属性是一个 boolean 类型,如果在 protocol 中的冒号后需要两个 ASCII 斜杠字符(/),则其值为 true

【The slashes property is a boolean with a value of true if two ASCII forward-slash characters (/) are required following the colon in the protocol.】

url.format(urlObject)#>

稳定性: 3 - 传统做法:请改用 WHATWG URL API。

  • urlObject <Object> | <string> 一个 URL 对象(由 url.parse() 返回或通过其他方式构建)。如果是字符串,则通过将其传递给 url.parse() 转换为对象。

url.format() 方法返回一个根据 urlObject 生成的格式化 URL 字符串。

【The url.format() method returns a formatted URL string derived from urlObject.】

const url = require('node:url');
url.format({
  protocol: 'https',
  hostname: 'example.com',
  pathname: '/some/path',
  query: {
    page: 1,
    format: 'json',
  },
});

// => 'https://example.com/some/path?page=1&format=json' 

如果 urlObject 不是对象或字符串,url.format() 将抛出一个 TypeError

【If urlObject is not an object or a string, url.format() will throw a TypeError.】

格式化过程如下:

【The formatting process operates as follows:】

  • 创建了一个新的空字符串 result
  • 如果 urlObject.protocol 是一个字符串,它会原样追加到 result 中。
  • 否则,如果 urlObject.protocol 不是 undefined 且不是字符串,将抛出 Error
  • 对于所有 urlObject.protocol 的字符串值,如果 不以 ASCII 冒号(:)结尾,则字面字符串 : 将被附加到 result
  • 如果以下任一条件为真,则字面字符串 // 将被附加到 result
    • urlObject.slashes 属性为 true;
    • urlObject.protocolhttphttpsftpgopherfile 开头;
  • 如果 urlObject.auth 属性的值为真值,并且 urlObject.hosturlObject.hostname 不是 undefinedurlObject.auth 的值将被强制转换为字符串并附加到 result 后面,后跟字面量字符串 @
  • 如果 urlObject.host 属性是 undefined,那么:
    • 如果 urlObject.hostname 是一个字符串,它将被添加到 result 中。
    • 否则,如果 urlObject.hostname 不是 undefined 且不是字符串,将抛出 Error
    • 如果 urlObject.port 属性值为真,并且 urlObject.hostname 不是 undefined
      • 字面字符串 : 被附加到 result,并且
      • urlObject.port 的值会被强制转换为字符串并追加到 result 中。
  • 否则,如果 urlObject.host 属性的值为真值,则将 urlObject.host 的值强制转换为字符串并附加到 result
  • 如果 urlObject.pathname 属性是一个非空字符串:
    • 如果 urlObject.pathname 不以 ASCII 斜杠 (/) 开头,那么字面字符串 '/' 会被追加到 result
    • urlObject.pathname 的值会被添加到 result 中。
  • 否则,如果 urlObject.pathname 不是 undefined 且不是字符串,将抛出 Error
  • 如果 urlObject.search 属性是 undefined,且 urlObject.query 属性是一个 Object,则会在 result 后追加字面字符串 ?,然后是调用 querystring 模块的 stringify() 方法并传入 urlObject.query 值的输出。
  • 否则,如果 urlObject.search 是一个字符串:
    • 如果 urlObject.search 的值不以 ASCII 问号字符 (?) 开头,则将字面字符串 ? 附加到 result
    • urlObject.search 的值会被添加到 result 中。
  • 否则,如果 urlObject.search 不是 undefined 且不是字符串,将抛出 Error
  • 如果 urlObject.hash 属性是一个字符串:
    • 如果 urlObject.hash 的值 不以 ASCII 井号(#)字符开头,则文字字符串 # 会被追加到 result 中。
    • urlObject.hash 的值会被添加到 result 中。
  • 否则,如果 urlObject.hash 属性不是 undefined 且不是字符串,将会抛出 Error 错误。
  • result 被返回。

url.parse(urlString[, parseQueryString[, slashesDenoteHost]])#>

稳定性: 0 - 已弃用:请改用 WHATWG URL API。

  • urlString <string> 要解析的 URL 字符串。
  • parseQueryString <boolean> 如果为 truequery 属性将始终被设置为由 querystring 模块的 parse() 方法返回的对象。如果为 false,返回的 URL 对象上的 query 属性将是未解析、未解码的字符串。默认值: false
  • slashesDenoteHost <boolean> 如果为 true,字面字符串 // 之后并且下一个 / 之前的第一个标记将被解释为 host。例如,给定 //foo/bar,结果将是 {host: 'foo', pathname: '/bar'} 而不是 {pathname: '//foo/bar'}默认值: false

url.parse() 方法接收一个 URL 字符串,对其进行解析,并返回一个 URL 对象。

【The url.parse() method takes a URL string, parses it, and returns a URL object.】

如果 urlString 不是字符串,将抛出 TypeError

【A TypeError is thrown if urlString is not a string.】

如果存在 auth 属性但无法解码,则会抛出 URIError

【A URIError is thrown if the auth property is present but cannot be decoded.】

url.parse() 使用宽松的、非标准的算法来解析 URL 字符串。它容易出现安全问题,例如 主机名欺骗,以及对用户名和密码处理不正确。不要在不受信任的输入上使用它。对于 url.parse() 漏洞不会发布 CVE。请改用 WHATWG URL API。

url.resolve(from, to)#>

稳定性: 3 - 传统做法:请改用 WHATWG URL API。

  • from <string> 如果 to 是相对 URL,则使用的基础 URL。
  • to <string> 要解析的目标 URL。

url.resolve() 方法以类似于网页浏览器解析锚点标签的方式,解析相对于基 URL 的目标 URL。

【The url.resolve() method resolves a target URL relative to a base URL in a manner similar to that of a web browser resolving an anchor tag.】

const url = require('node:url');
url.resolve('/one/two/three', 'four');         // '/one/two/four'
url.resolve('http://example.com/', '/one');    // 'http://example.com/one'
url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' 

使用 WHATWG URL API 实现相同的结果:

【To achieve the same result using the WHATWG URL API:】

function resolve(from, to) {
  const resolvedUrl = new URL(to, new URL(from, 'resolve://'));
  if (resolvedUrl.protocol === 'resolve:') {
    // `from` is a relative URL.
    const { pathname, search, hash } = resolvedUrl;
    return pathname + search + hash;
  }
  return resolvedUrl.toString();
}

resolve('/one/two/three', 'four');         // '/one/two/four'
resolve('http://example.com/', '/one');    // 'http://example.com/one'
resolve('http://example.com/one', '/two'); // 'http://example.com/two' 

URL 中的百分比编码#>

【Percent-encoding in URLs】

URL 只允许包含一定范围的字符。任何超出该范围的字符都必须进行编码。如何编码这些字符,以及哪些字符需要编码,完全取决于该字符在 URL 结构中的位置。

【URLs are permitted to only contain a certain range of characters. Any character falling outside of that range must be encoded. How such characters are encoded, and which characters to encode depends entirely on where the character is located within the structure of the URL.】

旧版 API#>

【Legacy API】

在 Legacy API 中,URL 对象的属性中的空格(' ')和以下字符将会被自动转义:

【Within the Legacy API, spaces (' ') and the following characters will be automatically escaped in the properties of URL objects:】

< > " ` \r \n \t { } | \ ^ ' 

例如,ASCII 空格字符(' ')被编码为 %20。ASCII 斜杠字符(/)被编码为 %3C

【For example, the ASCII space character (' ') is encoded as %20. The ASCII forward slash (/) character is encoded as %3C.】

WHATWG API#>

WHATWG URL 标准 在选择编码字符时采用的方式比传统 API 更有选择性且更精细。

【The WHATWG URL Standard uses a more selective and fine grained approach to selecting encoded characters than that used by the Legacy API.】

WHATWG 算法定义了四个“百分比编码集”,用于描述必须进行百分比编码的字符范围:

【The WHATWG algorithm defines four "percent-encode sets" that describe ranges of characters that must be percent-encoded:】

  • C0 控制百分号编码集合 包括范围从 U+0000 到 U+001F(含)以及所有大于 U+007E (~) 的代码点。
  • 片段百分比编码集合 包括 C0 控制百分比编码集合 以及代码点 U+0020 空格、U+0022 (")、U+003C (<), U+003E (>) 和 U+0060 (`)。
  • 路径百分号编码集合 包括 C0 控制百分号编码集合 以及代码点 U+0020 空格、U+0022 (")、U+0023 (#)、U+003C (<), U+003E (>)、U+003F (?)、U+0060 (`)、U+007B ({) 和 U+007D (})。
  • userinfo 编码集 包括 path 百分比编码集 以及码点 U+002F (/)、U+003A (:)、U+003B (;)、U+003D (=)、U+0040 (@)、U+005B ([) 到 U+005E (^) 和 U+007C (|)。

userinfo 百分号编码集 专门用于 URL 中编码的用户名和密码。path 百分号编码集 用于大多数 URL 的路径。fragment 百分号编码集 用于 URL 的片段。C0 控制百分号编码集 在某些特定情况下用于主机和路径,除此之外还用于所有其他情况。

【The userinfo percent-encode set is used exclusively for username and passwords encoded within the URL. The path percent-encode set is used for the path of most URLs. The fragment percent-encode set is used for URL fragments. The C0 control percent-encode set is used for host and path under certain specific conditions, in addition to all other cases.】

当主机名中出现非 ASCII 字符时,主机名会使用 Punycode 算法进行编码。但是,请注意,主机名可能同时包含 Punycode 编码和百分号编码的字符:

【When non-ASCII characters appear within a host name, the host name is encoded using the Punycode algorithm. Note, however, that a host name may contain both Punycode encoded and percent-encoded characters:】

const myURL = new URL('https://%CF%80.example.com/foo');
console.log(myURL.href);
// Prints https://xn--1xa.example.com/foo
console.log(myURL.origin);
// Prints https://xn--1xa.example.com 
Node.js 中文网 - 粤ICP备13048890号