url 网址
History
稳定性:2 - 稳定
node:url 模块提供了用于 URL 解析和解析的实用工具。它
可以通过以下方式访问:
import url from 'node:url';URL 字符串是包含多个有意义组成部分的结构化字符串。 解析后,将返回一个 URL 对象,其中包含这些 组成部分各自的属性。
node:url 模块提供了两个用于处理 URL 的 API:一个是旧版 API,它是
Node.js 特有的;另一个实现了与 Web 浏览器所使用的相同的
WHATWG URL 标准 的较新 API。
下面提供了 WHATWG API 与旧版 API 之间的比较。在 URL
'https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash' 上方,展示了
由旧版 url.parse() 返回的对象的属性。下方是
WHATWG URL 对象的属性。
WHATWG URL 的 origin 属性包含 protocol 和 host,但不包含
username 或 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 解析 URL 字符串:
const myURL =
new URL('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');使用旧版 API 解析 URL 字符串:
import url from 'node:url';
const myURL =
url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');可以使用属性设置器或模板字面量字符串从各个组成部分构造一个 WHATWG URL:
const myURL = new URL('https://example.org');
myURL.pathname = '/a/b/c';
myURL.search = '?d=e';
myURL.hash = '#fgh';要获取构造后的 URL 字符串,请使用 href 属性访问器:
console.log(myURL.href);类:URL
History
现在该类可在全局对象上使用。
与浏览器兼容的 URL 类,通过遵循 WHATWG URL
标准实现。已解析 URL 的示例可在该标准本身中找到。
URL 类也可在全局对象上使用。
按照浏览器惯例,URL 对象的所有属性
都实现为类原型上的 getter 和 setter,而不是
对象自身的数据属性。因此,与旧版 urlObject不同,
在 URL 对象的任何属性上使用 delete 关键字(例如 delete myURL.protocol、delete myURL.pathname等)不起作用,但仍会 返回true`。
new URL(input, base?): void通过相对于 base 解析 input 来创建一个新的 URL 对象。如果
base 以字符串形式传入,则对它的解析等同于 new URL(base)。
const myURL = new URL('/foo', 'https://example.org/');
// https://example.org/fooURL 构造函数可作为全局对象上的属性访问。 也可以从内置的 url 模块中导入:
import { URL } from 'node:url';
console.log(URL === globalThis.URL); // Prints 'true'.如果 input 或 base 不是有效的 URL,将抛出 TypeError。请注意,
将尝试将给定的值强制转换为字符串。
例如:
const myURL = new URL({ toString: () => 'https://example.org/' });
// https://example.org/input 主机名中出现的 Unicode 字符将
使用 Punycode 算法自动转换为 ASCII。
const myURL = new URL('https://測試');
// https://xn--g6w251d/如果事先无法确定 input 是否为绝对 URL,
并且提供了 base,建议验证 URL 对象的 origin
是否符合预期。
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/- 类型:
<string>
获取和设置 URL 的片段部分。
const myURL = new URL('https://example.org/foo#bar');
console.log(myURL.hash);
// 打印 #bar
myURL.hash = 'baz';
console.log(myURL.href);
// 打印 https://example.org/foo#baz赋给 hash 属性的值中包含的无效 URL 字符
将被百分号编码。选择哪些字符进行
百分号编码,可能与 url.parse()
和 url.format() 方法产生的结果略有不同。
- 类型:
<string>
获取和设置 URL 的主机部分。
const myURL = new URL('https://example.org:81/foo');
console.log(myURL.host);
// 打印 example.org:81
myURL.host = 'example.com:82';
console.log(myURL.href);
// 打印 https://example.com:82/foo赋给 host 属性的无效主机值将被忽略。
- 类型:
<string>
获取和设置 URL 的主机名部分。url.host 与 url.hostname 之间的
主要区别在于 url.hostname 不 包含
端口。
const myURL = new URL('https://example.org:81/foo');
console.log(myURL.hostname);
// 打印 example.org
// 设置 hostname 不会改变端口
myURL.hostname = 'example.com';
console.log(myURL.href);
// 打印 https://example.com:81/foo
// 使用 myURL.host 来更改主机名和端口
myURL.host = 'example.org:82';
console.log(myURL.href);
// 打印 https://example.org:82/foo赋给 hostname 属性的无效主机名值将被忽略。
- 类型:
<string>
获取和设置序列化后的 URL。
const myURL = new URL('https://example.org/foo');
console.log(myURL.href);
// 打印 https://example.org/foo
myURL.href = 'https://example.com/bar';
console.log(myURL.href);
// 打印 https://example.com/bar获取 href 属性的值等同于调用
url.toString()。
将此属性的值设置为新值等同于使用 new URL(value)
创建一个新的 URL 对象。每个 URL
对象的属性都将被修改。
如果赋给 href 属性的值不是有效的 URL,将抛出
TypeError。
- 类型:
<string>
- 类型:
<string>
获取 URL 源的只读序列化表示。
const myURL = new URL('https://example.org/foo/bar?baz');
console.log(myURL.origin);
// 打印 https://example.org- 类型:
<string>
获取和设置 URL 的密码部分。
const myURL = new URL('https://abc:xyz@example.com');
console.log(myURL.password);
// 打印 xyz
myURL.password = '123';
console.log(myURL.href);
// 打印 https://abc:123@example.com/赋给 password 属性的值中包含的无效 URL 字符
将被百分号编码。选择哪些字符进行
百分号编码,可能与 url.parse()
和 url.format() 方法产生的结果略有不同。
- 类型:
<string>
获取和设置 URL 的路径部分。
const myURL = new URL('https://example.org/abc/xyz?123');
console.log(myURL.pathname);
// 打印 /abc/xyz
myURL.pathname = '/abcdef';
console.log(myURL.href);
// 打印 https://example.org/abcdef?123赋给 pathname 属性的值中包含的无效 URL
字符将被百分号编码。选择哪些字符
进行百分号编码,可能与 url.parse()
和 url.format() 方法产生的结果略有不同。
- 类型:
<string>
获取和设置 URL 的端口部分。
端口值可以是一个数字,或一个包含 0 到 65535(含)范围内数字的
字符串。如果将该值设置为给定 protocol 的 URL 对象的默认端口,
则 port 的值将变为
空字符串('')。
端口值可以是空字符串,在这种情况下,端口取决于 协议/方案:
| 协议 | 端口 |
|---|---|
| "ftp" | 21 |
| "file" | |
| "http" | 80 |
| "https" | 443 |
| "ws" | 80 |
| "wss" | 443 |
为端口赋值时,该值将首先使用 .toString() 转换为
字符串。
如果该字符串无效但以数字开头,则前面的数字将被
赋给 port。
如果该数字超出上述范围,则会被忽略。
const myURL = new URL('https://example.org:8888');
console.log(myURL.port);
// 打印 8888
// 默认端口会自动转换为空字符串
// (HTTPS 协议的默认端口是 443)
myURL.port = '443';
console.log(myURL.port);
// 打印空字符串
console.log(myURL.href);
// 打印 https://example.org/
myURL.port = 1234;
console.log(myURL.port);
// 打印 1234
console.log(myURL.href);
// 打印 https://example.org:1234/
// 完全无效的端口字符串会被忽略
myURL.port = 'abcd';
console.log(myURL.port);
// 打印 1234
// 开头的数字会被视为端口号
myURL.port = '5678abcd';
console.log(myURL.port);
// 打印 5678
// 非整数会被截断
myURL.port = 1234.5678;
console.log(myURL.port);
// 打印 1234
// 未以科学计数法表示但超出范围的数字
// 将被忽略。
myURL.port = 1e10; // 10000000000, will be range-checked as described below
console.log(myURL.port);
// 打印 1234包含小数点的数字, 例如浮点数或用科学计数法表示的数字, 也不例外于此规则。 小数点之前的前导数字将被设置为 URL 的端口, 前提是它们有效:
myURL.port = 4.567e21;
console.log(myURL.port);
// 打印 4(因为它是字符串 '4.567e21' 中的前导数字)- 类型:
<string>
获取和设置 URL 的协议部分。
const myURL = new URL('https://example.org');
console.log(myURL.protocol);
// 打印 https:
myURL.protocol = 'ftp';
console.log(myURL.href);
// 打印 ftp://example.org/赋给 protocol 属性的无效 URL 协议值将被忽略。
WHATWG URL 标准 认为少数 URL 协议方案
在解析和序列化方式上是_特殊的_。当 URL 使用其中一种
特殊协议进行解析时,url.protocol 属性
可以更改为另一种特殊协议,但不能更改为
非特殊协议,反之亦然。
例如,从 http 更改为 https 是可行的:
const u = new URL('http://example.org');
u.protocol = 'https';
console.log(u.href);
// https://example.org/但是,从 http 更改为假想的 fish 协议则不行,
因为新协议不是特殊协议。
const u = new URL('http://example.org');
u.protocol = 'fish';
console.log(u.href);
// http://example.org/同样,从非特殊协议更改为特殊协议也是 不允许的:
const u = new URL('fish://example.org');
u.protocol = 'http';
console.log(u.href);
// fish://example.org根据 WHATWG URL 标准,特殊协议方案有 ftp、
file、http、https、ws 和 wss。
- 类型:
<string>
获取和设置 URL 的序列化查询部分。
const myURL = new URL('https://example.org/abc?123');
console.log(myURL.search);
// 打印 ?123
myURL.search = 'abc=xyz';
console.log(myURL.href);
// 打印 https://example.org/abc?abc=xyz赋给 search 属性的值中出现的任何无效 URL 字符
将被百分号编码。选择哪些
字符进行百分号编码,可能与 url.parse()
和 url.format() 方法产生的结果略有不同。
获取表示 URL 查询参数的 URLSearchParams
对象。此属性是只读的,但它提供的 URLSearchParams 对象
可用于修改 URL 实例;要替换 URL 的全部查询
参数,请使用 url.search 的 setter。有关详情,
请参阅 URLSearchParams 文档。
使用 .searchParams 修改 URL 时要小心,因为
根据 WHATWG 规范,URLSearchParams 对象使用
不同的规则来确定哪些字符需要百分号编码。例
如,URL 对象不会对 ASCII 波浪号(~)字符
进行百分号编码,而 URLSearchParams 始终会对其进行编码:
const myURL = new URL('https://example.org/abc?foo=~bar');
console.log(myURL.search); // prints ?foo=~bar
// 通过 searchParams 修改 URL...
myURL.searchParams.sort();
console.log(myURL.search); // prints ?foo=%7Ebar- 类型:
<string>
获取和设置 URL 的用户名部分。
const myURL = new URL('https://abc:xyz@example.com');
console.log(myURL.username);
// 打印 abc
myURL.username = '123';
console.log(myURL.href);
// 打印 https://123:xyz@example.com/赋给 username 属性的值中出现的任何无效 URL 字符
将被百分号编码。选择哪些
字符进行百分号编码,可能与 url.parse()
和 url.format() 方法产生的结果略有不同。
url.toString(): void- 返回:
<string>
URL 对象上的 toString() 方法返回序列化后的 URL。返回的
值等同于 url.href 和 url.toJSON() 的返回值。
url.toJSON(): void- 返回:
<string>
URL 对象上的 toJSON() 方法返回序列化后的 URL。返回的
值等同于 url.href 和
url.toString() 的返回值。
当一个 URL 对象通过 JSON.stringify() 序列化时,
会自动调用此方法。
const myURLs = [
new URL('https://www.example.com'),
new URL('https://test.example.org'),
];
console.log(JSON.stringify(myURLs));
// 打印 ["https://www.example.com/","https://test.example.org/"]URL.createObjectURL(blob): void<Blob>创建一个 'blob:nodedata:...' URL 字符串,它表示给定的 <Blob>
对象,并可用于稍后检索该 Blob。
const {
Blob,
resolveObjectURL,
} = require('node:buffer');
const blob = new Blob(['hello']);
const id = URL.createObjectURL(blob);
// 稍后...
const otherBlob = resolveObjectURL(id);
console.log(otherBlob.size);已注册的 <Blob> 所存储的数据将保留在内存中,直到
调用 URL.revokeObjectURL() 将其移除。
Blob 对象在当前线程内注册。如果使用 Worker
线程,则在一个 Worker 中注册的 Blob 对象将无法
供其他 Worker 或主线程使用。
URL.revokeObjectURL(id): void<string>URL.createObjectURL()
返回的
'blob:nodedata:...
URL 字符串。移除由给定 ID 标识的已存储 <Blob>。尝试撤销
未注册的 ID 将以静默方式失败。
URL.canParse(input, base?): void检查相对于 base 的 input 是否可以解析为 URL。
const isValid = URL.canParse('/foo', 'https://example.org/'); // true
const isNotValid = URL.canParse('/foo'); // falseURL.parse(input, base?): void将字符串解析为 URL。如果提供了 base,它将用作
解析非绝对 input URL 的基准 URL。如果参数无法解析为
有效的 URL,则返回 null。
类:URLPattern
History
稳定性:1 - 实验性
URLPattern API 提供了一个接口,用于根据模式匹配 URL 或 URL 的
各个部分。
const myPattern = new URLPattern('https://nodejs.org/docs/latest/api/*.html');
console.log(myPattern.exec('https://nodejs.org/docs/latest/api/dns.html'));
// 打印:
// {
// "hash": { "groups": { "0": "" }, "input": "" },
// "hostname": { "groups": {}, "input": "nodejs.org" },
// "inputs": [
// "https://nodejs.org/docs/latest/api/dns.html"
// ],
// "password": { "groups": { "0": "" }, "input": "" },
// "pathname": { "groups": { "0": "dns" }, "input": "/docs/latest/api/dns.html" },
// "port": { "groups": {}, "input": "" },
// "protocol": { "groups": {}, "input": "https" },
// "search": { "groups": { "0": "" }, "input": "" },
// "username": { "groups": { "0": "" }, "input": "" }
// }
console.log(myPattern.test('https://nodejs.org/docs/latest/api/dns.html'));
// 打印:truenew URLPattern(): void实例化一个新的空 URLPattern 对象。
new URLPattern(string, baseURL?, options?): void将 string 解析为 URL,并使用它来实例化一个新的
URLPattern 对象。
如果未指定 baseURL,则默认为 undefined。
选项可以具有 ignoreCase 布尔属性,如果设置为 true,则启用
不区分大小写的匹配。
构造函数可能会抛出 TypeError 以指示解析失败。
new URLPattern(obj, baseURL?, options?): void将 Object 解析为输入模式,并使用它来实例化一个新的
URLPattern 对象。对象成员可以是 protocol、username、
password、hostname、port、pathname、search、hash 或 baseURL。
如果未指定 baseURL,则默认为 undefined。
选项可以具有 ignoreCase 布尔属性,如果设置为 true,则启用
不区分大小写的匹配。
构造函数可能会抛出 TypeError 以指示解析失败。
urlPattern.exec(input, baseURL?): void<string>
|
<undefined>输入可以是字符串,也可以是提供各个 URL 组成部分的对象。
对象成员可以是 protocol、username、password、hostname、
port、pathname、search、hash 或 baseURL。
如果未指定 baseURL,则默认为 undefined。
返回一个对象,其中的 inputs 键包含传入函数的参数数组,
以及 URL 各组成部分的键,这些键包含匹配的输入和
匹配的分组。
const myPattern = new URLPattern('https://nodejs.org/docs/latest/api/*.html');
console.log(myPattern.exec('https://nodejs.org/docs/latest/api/dns.html'));
// 打印:
// {
// "hash": { "groups": { "0": "" }, "input": "" },
// "hostname": { "groups": {}, "input": "nodejs.org" },
// "inputs": [
// "https://nodejs.org/docs/latest/api/dns.html"
// ],
// "password": { "groups": { "0": "" }, "input": "" },
// "pathname": { "groups": { "0": "dns" }, "input": "/docs/latest/api/dns.html" },
// "port": { "groups": {}, "input": "" },
// "protocol": { "groups": {}, "input": "https" },
// "search": { "groups": { "0": "" }, "input": "" },
// "username": { "groups": { "0": "" }, "input": "" }
// }urlPattern.test(input, baseURL?): boolean输入可以是字符串,也可以是提供各个 URL 组成部分的对象。
对象成员可以是 protocol、username、password、hostname、
port、pathname、search、hash 或 baseURL。
如果未指定 baseURL,则默认为 undefined。
返回一个布尔值,指示输入是否匹配当前模式。
const myPattern = new URLPattern('https://nodejs.org/docs/latest/api/*.html');
console.log(myPattern.test('https://nodejs.org/docs/latest/api/dns.html'));
// 打印:true类:URLSearchParams
History
该类现在可在全局对象上使用。
URLSearchParams API 提供对 URL 查询的读写访问。
URLSearchParams 类也可以使用以下四种构造函数
之一单独使用。
URLSearchParams 类也可在全局对象上使用。
WHATWG URLSearchParams 接口与 querystring 模块有着
相似的用途,但 querystring 模块的用途更为
通用,因为它允许自定义分隔符字符(& 和 =)。
另一方面,此 API 专为 URL 查询字符串而设计。
const myURL = new URL('https://example.org/?abc=123');
console.log(myURL.searchParams.get('abc'));
// 打印 123
myURL.searchParams.append('abc', 'xyz');
console.log(myURL.href);
// 打印 https://example.org/?abc=123&abc=xyz
myURL.searchParams.delete('abc');
myURL.searchParams.set('a', 'b');
console.log(myURL.href);
// 打印 https://example.org/?a=b
const newSearchParams = new URLSearchParams(myURL.searchParams);
// 上述代码等价于
// const newSearchParams = new URLSearchParams(myURL.search);
newSearchParams.append('a', 'c');
console.log(myURL.href);
// 打印 https://example.org/?a=b
console.log(newSearchParams.toString());
// 打印 a=b&a=c
// 隐式调用了 newSearchParams.toString()
myURL.search = newSearchParams;
console.log(myURL.href);
// 打印 https://example.org/?a=b&a=c
newSearchParams.delete('a');
console.log(myURL.href);
// 打印 https://example.org/?a=b&a=cnew URLSearchParams(): void实例化一个新的空 URLSearchParams 对象。
new URLSearchParams(string): void<string>将 string 解析为查询字符串,并使用它来实例化一个新的
URLSearchParams 对象。开头的 '?'(如果存在)会被忽略。
let params;
params = new URLSearchParams('user=abc&query=xyz');
console.log(params.get('user'));
// 打印 'abc'
console.log(params.toString());
// 打印 'user=abc&query=xyz'
params = new URLSearchParams('?user=abc&query=xyz');
console.log(params.toString());
// 打印 'user=abc&query=xyz'new URLSearchParams(obj): void<Object>使用查询哈希映射实例化一个新的 URLSearchParams 对象。
obj 每个属性的键和值始终会被强制转换为字符串。
与 querystring 模块不同,不允许以数组形式出现的
重复键。数组会使用 array.toString() 进行字符串化,它只是
用逗号连接所有数组元素。
const params = new URLSearchParams({
user: 'abc',
query: ['first', 'second'],
});
console.log(params.getAll('query'));
// 打印 [ 'first,second' ]
console.log(params.toString());
// 打印 'user=abc&query=first%2Csecond'new URLSearchParams(iterable): void<Iterable>以类似于 <Map> 构造函数的方式,使用可迭代映射来
实例化一个新的 URLSearchParams 对象。iterable 可以是 Array 或任何
可迭代对象。这意味着 iterable 可以是另一个 URLSearchParams,
在这种情况下,构造函数只会创建所提供
URLSearchParams 的克隆。iterable 的元素是键值对,
其本身可以是任何可迭代对象。
允许重复的键。
let params;
// 使用数组
params = new URLSearchParams([
['user', 'abc'],
['query', 'first'],
['query', 'second'],
]);
console.log(params.toString());
// 打印 'user=abc&query=first&query=second'
// 使用 Map 对象
const map = new Map();
map.set('user', 'abc');
map.set('query', 'xyz');
params = new URLSearchParams(map);
console.log(params.toString());
// 打印 'user=abc&query=xyz'
// 使用生成器函数
function* getQueryPairs() {
yield ['user', 'abc'];
yield ['query', 'first'];
yield ['query', 'second'];
}
params = new URLSearchParams(getQueryPairs());
console.log(params.toString());
// 打印 'user=abc&query=first&query=second'
// 每个键值对必须恰好包含两个元素
new URLSearchParams([
['user', 'abc', 'error'],
]);
// 抛出 TypeError [ERR_INVALID_TUPLE]:
// 每个查询对必须是可迭代的 [name, value] 元组urlSearchParams.append(name, value): void向查询字符串追加一个新的名称-值对。
urlSearchParams.delete(name, value?): void如果提供了 value,则移除所有
名称为 name 且值为 value 的名称-值对。。
如果未提供 value,则移除所有名称为 name 的名称-值对。
urlSearchParams.entries(): Iterator<Iterator>返回一个 ES6 Iterator,用于遍历查询中的每个名称-值对。
迭代器的每一项都是一个 JavaScript Array。Array 的第一项
是 name,第二项是 value。
urlSearchParams[Symbol.iterator]() 的别名。
urlSearchParams.forEach(fn, thisArg?): void<Function><Object>fn
时用作
this
的值遍历查询中的每个名称-值对,并调用给定的函数。
const myURL = new URL('https://example.org/?a=b&c=d');
myURL.searchParams.forEach((value, name, searchParams) => {
console.log(name, value, myURL.searchParams === searchParams);
});
// 打印:
// a b true
// c d trueurlSearchParams.get(name): void<string>返回名称为 name 的第一个名称-值对的值。如果
没有这样的名称-值对,则返回 null。
urlSearchParams.getAll(name): string返回名称为 name 的所有名称-值对的值。如果没有
这样的名称-值对,则返回一个空数组。
urlSearchParams.has(name, value?): boolean检查 URLSearchParams 对象是否包含基于 name 和可选的
value 参数的键值对。
如果提供了 value,则当存在具有相同
name 和 value 的名称-值对时返回 true。
如果未提供 value,则当至少有一个名称为 name
的名称-值对时返回 true。
urlSearchParams.keys(): Iterator<Iterator>返回一个 ES6 Iterator,用于遍历每个名称-值对的名称。
const params = new URLSearchParams('foo=bar&foo=baz');
for (const name of params.keys()) {
console.log(name);
}
// 打印:
// foo
// foourlSearchParams.set(name, value): void将 URLSearchParams 对象中与 name 关联的值设置为
value。如果存在任何名称已为 name 的名称-值对,
则将第一个此类对的值设置为 value,并移除其余所有对。否则,
将该名称-值对追加到查询字符串中。
const params = new URLSearchParams();
params.append('foo', 'bar');
params.append('foo', 'baz');
params.append('abc', 'def');
console.log(params.toString());
// 打印 foo=bar&foo=baz&abc=def
params.set('foo', 'def');
params.set('xyz', 'opq');
console.log(params.toString());
// 打印 foo=def&abc=def&xyz=opq参数条目的总数。
urlSearchParams.sort(): void按名称对所有现有的名称-值对进行原地排序。排序采用 稳定排序算法,因此名称相同的名称-值对之间的相对 顺序会被保留。
此方法尤其可用于提高缓存命中率。
const params = new URLSearchParams('query[]=abc&type=search&query[]=123');
params.sort();
console.log(params.toString());
// 打印 query%5B%5D=abc&query%5B%5D=123&type=searchurlSearchParams.toString(): string<string>返回序列化为字符串的查询参数,必要时会对字符 进行百分号编码。
urlSearchParams.values(): Iterator<Iterator>返回一个 ES6 Iterator,用于遍历每个名称-值对的值。
urlSearchParams[Symbol.iterator](): Iterator<Iterator>返回一个 ES6 Iterator,用于遍历查询字符串中的每个名称-值对。
迭代器的每一项都是一个 JavaScript Array。Array 的第一项
是 name,第二项是 value。
urlSearchParams.entries() 的别名。
const params = new URLSearchParams('foo=bar&xyz=baz');
for (const [name, value] of params) {
console.log(name, value);
}
// 打印:
// foo bar
// xyz bazurl.domainToASCII(domain): string返回 domain 的 Punycode ASCII 序列化。如果 domain 是
无效域名,则返回空字符串。
它执行 url.domainToUnicode() 的逆操作。
import url from 'node:url';
console.log(url.domainToASCII('español.com'));
// 打印 xn--espaol-zwa.com
console.log(url.domainToASCII('中文.com'));
// 打印 xn--fiq228c.com
console.log(url.domainToASCII('xn--iñvalid.com'));
// 打印空字符串url.domainToUnicode(domain): string返回 domain 的 Unicode 序列化。如果 domain 是无效的
域名,则返回空字符串。
它执行 url.domainToASCII() 的逆操作。
import url from 'node:url';
console.log(url.domainToUnicode('xn--espaol-zwa.com'));
// 打印 español.com
console.log(url.domainToUnicode('xn--fiq228c.com'));
// 打印 中文.com
console.log(url.domainToUnicode('xn--iñvalid.com'));
// 打印空字符串url.fileURLToPath
History
现在可以使用 options 参数来确定 如何解析 path 参数。
url.fileURLToPath(url, options?): void<Object><boolean>
|
<undefined>path
应作为 Windows 文件
路径返回,则为
true
;posix 为
false
;
系统默认值为
undefined
。
默认值:
undefined
。此函数确保对百分号编码字符进行正确解码,并 确保生成跨平台有效的绝对路径字符串。
安全注意事项:
此函数会解码百分号编码字符,包括编码的点段
(%2e 作为 .,%2e%2e 作为 ..),然后对结果路径进行规范化。
这意味着编码的目录遍历序列(如 %2e%2e)会
被解码并作为实际路径遍历处理,即使编码的斜杠
(%2F、%5C)会被正确拒绝。
应用程序绝不能仅依赖 fileURLToPath() 来防止目录
遍历攻击。 请始终对返回的路径值执行显式的路径验证和安全检查,
以确保其保持在预期范围内,
然后再将其用于文件系统操作。
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)url.fileURLToPathBuffer(url, options?): void<Object><boolean>
|
<undefined>path
应作为 Windows 文件
路径返回,则为
true
;posix 为
false
;
系统默认值为
undefined
。
默认值:
undefined
。与 url.fileURLToPath(...) 类似,不同之处在于它返回的是
Buffer 而不是路径的字符串表示。当输入 URL 包含
不是有效 UTF-8 / Unicode 序列的百分号编码段时,
这种转换非常有用。
安全注意事项:
此函数与 url.fileURLToPath() 具有相同的安全注意事项。
它会解码百分号编码字符,包括编码的点段
(%2e 作为 .,%2e%2e 作为 ..),并对路径进行规范化。** 应用程序
绝不能仅依赖此函数来防止目录遍历攻击。**
在将返回的 buffer 值用于文件系统操作之前,
请始终对其执行显式的路径验证。
url.format(URL, options?): string<URL><Object><boolean>true
,否则为
false
。
默认值:
true
。<boolean>true
,否则为
false
。
默认值:
true
。<boolean>true
,否则为
false
。
默认值:
true
。<boolean>true
。
默认值:
false
。<string>返回 WHATWG URL 对象的 URL String 表示
形式的可自定义序列化结果。
URL 对象同时具有 toString() 方法和 href 属性,它们都会
返回 URL 的字符串序列化结果。但是,这些结果无法
以任何方式自定义。url.format(URL[, options]) 方法允许对
输出进行基本的自定义。
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'url.pathToFileURL
History
现在可以使用 options 参数来确定 如何返回 path 值。
url.pathToFileURL(path, options?): void<string><Object><boolean>
|
<undefined>path
应被视为 Windows 文件路径则为
true
,
如果为 posix 路径则为
false
,
如果为系统默认值则为
undefined
。
默认值:
undefined
。此函数确保 path 被解析为绝对路径,并且 URL
控制字符在转换为文件 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)url.urlToHttpOptions
History
返回的对象还将包含 url 参数的所有 自身可枚举属性。
url.urlToHttpOptions(url): void<URL><string><string><string><string><string><string>'/index.html?page=12'
。当请求路径包含非法字符时
将抛出异常。目前仅拒绝空格,但这在未来
可能会改变。<string><number><string>'user:password'
,用于计算
Authorization 头。此实用函数将 URL 对象转换为普通选项对象,
以供 http.request() 和 https.request() API 使用。
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'
}
*/稳定性:3 - 旧版:改用 WHATWG URL API。
旧版 urlObject(require('node:url').Url 或
import { Url } from 'node:url')由
url.parse() 函数创建并返回。
auth 属性是 URL 的用户名和密码部分,
也称为 userinfo。此字符串子集位于 protocol 和
双斜杠(如果存在)之后、host 组件之前,以 @ 分隔。
该字符串要么是用户名,要么是以 : 分隔的
用户名和密码。
例如:'user:pass'。
hash 属性是 URL 的片段标识符部分,包括前导
# 字符。
例如:'#hash'。
host 属性是 URL 的完整小写主机部分,
如果指定了 port,则包括该端口。
例如:'sub.example.com:8080'。
hostname 属性是 host 组件的小写主机名部分,
不包含 port。
例如:'sub.example.com'。
href 属性是解析后的完整 URL 字符串,其中
protocol 和 host 组件均已转换为小写。
例如:'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'。
path 属性是 pathname 和 search 组件的
串联。
例如:'/p/a/t/h?query=string'。
不会对 path 进行解码。
pathname 属性由 URL 的整个路径部分组成。它是
紧跟在 host(包括 port)之后、且在 query 或 hash 组件开始
之前的所有内容,以 ASCII 问号 (?) 或
井号 (#) 字符为分隔符。
例如:'/p/a/t/h'。
不会对该路径字符串进行解码。
port 属性是 host 组件中的数字端口部分。
例如:'8080'。
protocol 属性标识 URL 的小写协议方案。
例如:'http:'。
query 属性要么是不带前导 ASCII
问号 (?) 的查询字符串,要么是由 querystring 模块的
parse() 方法返回的对象。query 属性是字符串还是对象,
取决于传给 url.parse() 的 parseQueryString 参数。
例如:'query=string' 或 {'query': 'string'}。
如果以字符串形式返回,则不对查询字符串进行解码。如果 以对象形式返回,则键和值都会被解码。
search 属性由 URL 的整个"查询字符串"部分
组成,包括前导的 ASCII 问号 (?) 字符。
例如:'?query=string'。
不会对查询字符串进行解码。
slashes 属性是一个 boolean,如果在 protocol 中的冒号之后
需要两个 ASCII 正斜杠字符 (/),
则其值为 true。
url.format(urlObject): void<Object>url.parse()
返回
或以其他方式构造)。url.format() 方法返回一个基于
urlObject 生成的格式化 URL 字符串。
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。
格式化过程如下:
- 创建一个新的空字符串
result。 - 如果
urlObject.protocol是字符串,则将其原样附加到result。 - 否则,如果
urlObject.protocol不是undefined且不是字符串,则抛出Error。 - 对于所有 不以 ASCII 冒号 (
:) 结尾 的urlObject.protocol字符串值,将字面字符串:附加到result。 - 如果满足以下任一条件,则将字面字符串
//附加到result:urlObject.slashes属性为true;urlObject.protocol以http、https、ftp、gopher或file开头;
- 如果
urlObject.auth属性的值为真值,且urlObject.host或urlObject.hostname不是undefined,则 将urlObject.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。
可使用自动迁移(来源)。
npx codemod@latest @nodejs/node-url-to-whatwg-urlurl.format(urlString): void稳定性:0 - 已弃用:改用 WHATWG URL API。
<string>url.parse()
然后进行
格式化的字符串。url.format(urlString) 是 url.format(url.parse(urlString)) 的简写。
由于它在内部调用了已弃用的 url.parse(),因此向 url.format() 传递字符串参数
本身也已弃用。
可以使用 WHATWG URL API 来规范化 URL 字符串,方法是
构造一个新的 URL 对象并调用 url.toString()。
import { URL } from 'node:url';
const unformatted = 'http://[fe80:0:0:0:0:0:0:1]:/a/b?a=b#abc';
const formatted = new URL(unformatted).toString();
console.log(formatted); // Prints: http://[fe80::1]/a/b?a=b#abcurl.parse(urlString, parseQueryString?, slashesDenoteHost?): void稳定性:0 - 已弃用:改用 WHATWG URL API。
<string><boolean>true
,
query
属性将始终
设置为
querystring
模块的
parse()
方法返回的对象。
如果为
false
,返回的 URL 对象上的
query
属性将是
未解析、未解码的字符串。
默认值:
false
。<boolean>true
,字面字符串
//
之后、下一个
/
之前的
第一个标记将被解释为
host
。
例如,给定
//foo/bar
,结果为
{host: 'foo', pathname: '/bar'}
,而不是
{pathname: '//foo/bar'}
。
默认值:
false
。url.parse() 方法接受一个 URL 字符串,对其进行解析,并返回一个
URL 对象。
如果 urlString 不是字符串,则抛出 TypeError。
如果存在 auth 属性但无法解码,则抛出 URIError。
url.parse() 使用一种宽松的、非标准的算法来解析 URL
字符串。它容易出现安全问题,例如主机名欺骗
以及对用户名和密码的错误处理。请勿将其用于不可信
输入。url.parse() 的漏洞不会发布 CVE。请改用
WHATWG URL API,例如:
function getURL(req) {
const proto = req.headers['x-forwarded-proto'] || 'https';
const host = req.headers['x-forwarded-host'] || req.headers.host || 'example.com';
return new URL(`${proto}://${host}${req.url || '/'}`);
}上面的示例假设格式正确的标头会从反向 代理转发到你的 Node.js 服务器。如果你没有使用反向代理,则应 使用下面的示例:
function getURL(req) {
return new URL(`https://example.com${req.url || '/'}`);
}可使用自动迁移(来源)。
npx codemod@latest @nodejs/node-url-to-whatwg-urlurl.resolve(from, to): void稳定性:0 - 已弃用:改用 WHATWG URL API。
url.resolve() 方法以类似于 Web 浏览器解析锚点标签的方式,
相对于基准 URL 解析目标 URL。
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'由于它在内部调用了已弃用的 url.parse(),因此 url.resolve() 本身也已弃用。
要使用 WHATWG URL API 获得相同的结果:
function resolve(from, to) {
const resolvedUrl = new URL(to, new URL(from, 'resolve://'));
if (resolvedUrl.protocol === 'resolve:') {
// `from` 是一个相对 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 中只允许包含一定范围内的字符。任何超出 该范围的字符都必须进行编码。这些字符如何编码, 以及哪些字符需要编码,完全取决于该字符在 URL 结构中的 位置。
在旧版 API 中,空格 (' ') 和以下字符将
在 URL 对象的属性中自动转义:
< > " ` \r \n \t { } | \ ^ '例如,ASCII 空格字符 (' ') 被编码为 %20。ASCII
正斜杠 (/) 字符被编码为 %3C。
WHATWG URL 标准 使用了一种比旧版 API 更具选择性且更精细的方法来选择要编码的字符。
WHATWG 算法定义了四个"百分号编码集",用于描述 必须进行百分号编码的字符范围:
-
C0 控制百分号编码集 包括 U+0000 至 U+001F(含)范围内的码点,以及所有大于 U+007E (~) 的码点。
-
片段百分号编码集 包括 C0 控制百分号编码集 以及码点 U+0020 SPACE、U+0022 (")、U+003C (
<><<)、U+003E (>>)、 以及 U+0060 (`)。 -
路径百分号编码集 包括 C0 控制百分号编码集 以及码点 U+0020 SPACE、U+0022 (")、U+0023 (#)、U+003C (
<><<)、U+003E (>)、 U+003F (?)、U+0060 (`)、U+007B ({) 以及 U+007D (})。
-
userinfo 编码集 包括 路径百分号编码集 以及码点 U+002F (/)、U+003A (:)、U+003B (;)、U+003D (=)、U+0040 (@)、 U+005B ([) 至 U+005E(^),以及 U+007C (|)。
userinfo 百分号编码集 专门用于 URL 中 用户名和密码的编码。路径百分号编码集 用于 大多数 URL 的路径。片段百分号编码集 用于 URL 片段。 C0 控制百分号编码集 在某些特定条件下用于主机和路径, 此外还用于所有其他情况。
当主机名中出现非 ASCII 字符时,该主机名使用 Punycode 算法进行编码。但请注意,主机名 可能 同时包含 Punycode 编码和百分号编码的字符:
const myURL = new URL('https://%CF%80.example.com/foo');
console.log(myURL.href);
// 打印 https://xn--1xa.example.com/foo
console.log(myURL.origin);
// 打印 https://xn--1xa.example.com