Node.js v25.0.0 文档
- Node.js v25.0.0
-
目录
- URL
- URL 字符串和 URL 对象
- WHATWG URL API
- 类:
URL - 类:
URLPattern - 类:
URLSearchParamsnew URLSearchParams()new URLSearchParams(string)new URLSearchParams(obj)new URLSearchParams(iterable)urlSearchParams.append(name, value)urlSearchParams.delete(name[, value])urlSearchParams.entries()urlSearchParams.forEach(fn[, thisArg])urlSearchParams.get(name)urlSearchParams.getAll(name)urlSearchParams.has(name[, value])urlSearchParams.keys()urlSearchParams.set(name, value)urlSearchParams.sizeurlSearchParams.sort()urlSearchParams.toString()urlSearchParams.values()urlSearchParams[Symbol.iterator]()
url.domainToASCII(domain)url.domainToUnicode(domain)url.fileURLToPath(url[, options])url.fileURLToPathBuffer(url[, options])url.format(URL[, options])url.pathToFileURL(path[, options])url.urlToHttpOptions(url)
- 类:
- 旧版 URL API
- URL 中的百分号编码
- URL
-
索引
- 断言测试
- 异步上下文跟踪
- 异步钩子
- 缓冲区
- C++ 插件
- 使用 Node-API 的 C/C++ 插件
- C++ 嵌入器 API
- 子进程
- 集群
- 命令行选项
- 控制台
- 加密
- 调试器
- 已弃用的 API
- 诊断通道
- DNS
- 域
- 环境变量
- 错误
- 事件
- 文件系统
- 全局对象
- HTTP
- HTTP/2
- HTTPS
- 检查器
- 国际化
- 模块:CommonJS 模块
- 模块:ECMAScript 模块
- 模块:
node:moduleAPI - 模块:包
- 模块:TypeScript
- 网络
- 操作系统
- 路径
- 性能钩子
- 权限
- 进程
- Punycode
- 查询字符串
- 逐行读取
- REPL
- 报告
- 单一可执行文件应用
- SQLite
- 流
- 字符串解码器
- 测试运行器
- 定时器
- TLS/SSL
- 跟踪事件
- TTY
- UDP/数据报
- URL
- 实用工具
- V8
- 虚拟机
- WASI
- Web Crypto API
- Web Streams API
- 工作线程
- Zlib
- 其他版本
- 选项
URL#
源代码: lib/url.js
node:url 模块提供了用于 URL 解析和处理的实用工具。可以通过以下方式访问:
import url from 'node:url';const url = require('node:url');
URL 字符串和 URL 对象#
URL 字符串是一个包含多个有意义组件的结构化字符串。解析后,会返回一个 URL 对象,其中包含每个组件的属性。
node:url 模块提供了两种用于处理 URL 的 API:一个是 Node.js 特有的旧版 API,另一个是实现了与 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');const url = require('node:url');
const myURL =
url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');
从组件部分构造 URL 并获取构造的字符串#
可以使用属性设置器或模板字面量字符串从组件部分构造 WHATWG URL
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 属性访问器
console.log(myURL.href);
WHATWG URL API#
类:URL#
浏览器兼容的 URL 类,通过遵循 WHATWG URL 标准实现。解析后的 URL 示例可在标准本身中找到。URL 类也可在全局对象上使用。
根据浏览器惯例,URL 对象的所有属性都作为类原型上的 getter 和 setter 实现,而不是作为对象本身的数据属性。因此,与旧版 urlObject不同,对 URL 对象的任何属性使用 delete 关键字(例如 delete myURL.protocol、delete myURL.pathname 等)没有效果,但仍会返回 true。
new URL(input[, base])#
input<string> 要解析的绝对或相对输入 URL。如果input是相对的,则base是必需的。如果input是绝对的,则base会被忽略。如果input不是字符串,它会首先被转换为字符串。base<string> 如果input不是绝对 URL,则用作解析基准的 URL。如果base不是字符串,它会首先被转换为字符串。
通过相对于 base 解析 input 来创建一个新的 URL 对象。如果 base 作为字符串传递,它将被解析为等同于 new URL(base)。
const myURL = new URL('/foo', 'https://example.org/');
// https://example.org/foo
URL 构造函数可作为全局对象的属性访问。也可以从内置的 url 模块导入
import { URL } from 'node:url';
console.log(URL === globalThis.URL); // Prints 'true'.console.log(URL === require('node:url').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/
url.hash#
- 类型:<string>
获取并设置 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() 方法的产生结果略有不同。
url.host#
- 类型:<string>
获取并设置 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 属性的无效主机值将被忽略。
url.hostname#
- 类型:<string>
获取并设置 URL 的主机名部分。url.host 和 url.hostname 之间的主要区别在于 url.hostname 不包含端口。
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 属性的无效主机名值将被忽略。
url.href#
- 类型:<string>
获取并设置序列化的 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()。
将此属性的值设置为一个新值,等同于使用 new URL(value) 创建一个新的 URL 对象。URL 对象的每个属性都将被修改。
如果分配给 href 属性的值不是一个有效的 URL,则会抛出 TypeError。
url.origin#
- 类型:<string>
获取 URL 源的只读序列化表示。
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#
- 类型:<string>
获取并设置 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() 方法的产生结果略有不同。
url.pathname#
- 类型:<string>
获取并设置 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() 方法的产生结果略有不同。
url.port#
- 类型:<string>
获取并设置 URL 的端口部分。
端口值可以是一个数字或一个包含数字的字符串,范围在 0 到 65535(含)之间。将值设置为 URL 对象给定 protocol 的默认端口,将导致 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);
// 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 的端口,前提是它们是有效的
myURL.port = 4.567e21;
console.log(myURL.port);
// Prints 4 (because it is the leading number in the string '4.567e21')
url.protocol#
- 类型:<string>
获取并设置 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 协议值将被忽略。
特殊协议#
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。
url.search#
- 类型:<string>
获取并设置 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() 方法的产生结果略有不同。
url.searchParams#
获取表示 URL 查询参数的 URLSearchParams 对象。此属性是只读的,但它提供的 URLSearchParams 对象可用于修改 URL 实例;要替换 URL 的全部查询参数,请使用 url.search 设置器。有关详细信息,请参阅 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
// Modify the URL via searchParams...
myURL.searchParams.sort();
console.log(myURL.search); // prints ?foo=%7Ebar
url.username#
- 类型:<string>
获取并设置 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() 方法的产生结果略有不同。
url.toJSON()#
- 返回: <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));
// Prints ["https://www.example.com/","https://test.example.org/"]
URL.createObjectURL(blob)#
创建一个表示给定 <Blob> 对象的 'blob:nodedata:...' URL 字符串,该字符串可用于稍后检索 Blob。
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() 将其移除。
Blob 对象在当前线程内注册。如果使用工作线程,在一个工作线程中注册的 Blob 对象将对其他工作线程或主线程不可用。
URL.revokeObjectURL(id)#
id<string> 一个由先前调用URL.createObjectURL()返回的'blob:nodedata:...URL 字符串。
移除由给定 ID 标识的已存储 <Blob>。尝试撤销一个未注册的 ID 将会静默失败。
URL.canParse(input[, base])#
input<string> 要解析的绝对或相对输入 URL。如果input是相对的,则base是必需的。如果input是绝对的,则base会被忽略。如果input不是字符串,它会首先被转换为字符串。base<string> 如果input不是绝对 URL,则用作解析基准的 URL。如果base不是字符串,它会首先被转换为字符串。- 返回:<boolean>
检查相对于 base 的 input 是否可以解析为 URL。
const isValid = URL.canParse('/foo', 'https://example.org/'); // true
const isNotValid = URL.canParse('/foo'); // false
URL.parse(input[, base])#
input<string> 要解析的绝对或相对输入 URL。如果input是相对的,则base是必需的。如果input是绝对的,则base会被忽略。如果input不是字符串,它会首先被转换为字符串。base<string> 如果input不是绝对 URL,则用作解析基准的 URL。如果base不是字符串,它会首先被转换为字符串。- 返回:<URL> | <null>
将字符串解析为 URL。如果提供了 base,它将被用作解析非绝对 input URL 的基准 URL。如果参数无法解析为有效的 URL,则返回 null。
类:URLPattern#
URLPattern API 提供了一个接口,用于将 URL 或 URL 的一部分与模式进行匹配。
const myPattern = new URLPattern('https://node.org.cn/docs/latest/api/*.html');
console.log(myPattern.exec('https://node.org.cn/docs/latest/api/dns.html'));
// Prints:
// {
// "hash": { "groups": { "0": "" }, "input": "" },
// "hostname": { "groups": {}, "input": "nodejs.org" },
// "inputs": [
// "https://node.org.cn/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://node.org.cn/docs/latest/api/dns.html'));
// Prints: true
new URLPattern()#
实例化一个新的空 URLPattern 对象。
new URLPattern(string[, baseURL][, options])#
string<string> 一个 URL 字符串baseURL<string> | <undefined> 一个基础 URL 字符串options<Object> 选项
将 string 解析为 URL,并用它来实例化一个新的 URLPattern 对象。
如果未指定 baseURL,则默认为 undefined。
选项可以有一个 ignoreCase 布尔属性,如果设置为 true,则启用不区分大小写的匹配。
构造函数可能会抛出一个 TypeError 来表示解析失败。
new URLPattern(obj[, baseURL][, options])#
obj<Object> 一个输入模式baseURL<string> | <undefined> 一个基础 URL 字符串options<Object> 选项
将 Object 解析为输入模式,并用它来实例化一个新的 URLPattern 对象。该对象的成员可以是 protocol、username、password、hostname、port、pathname、search、hash 或 baseURL 中的任意一个。
如果未指定 baseURL,则默认为 undefined。
选项可以有一个 ignoreCase 布尔属性,如果设置为 true,则启用不区分大小写的匹配。
构造函数可能会抛出一个 TypeError 来表示解析失败。
urlPattern.exec(input[, baseURL])#
input<string> | <Object> 一个 URL 或 URL 的部分baseURL<string> | <undefined> 一个基础 URL 字符串
输入可以是一个字符串或一个提供各个 URL 部分的对象。对象成员可以是 protocol、username、password、hostname、port、pathname、search、hash 或 baseURL 中的任意一个。
如果未指定 baseURL,则默认为 undefined。
返回一个对象,其中包含一个 inputs 键,其值为传入函数的参数数组,以及 URL 组件的键,其中包含匹配的输入和匹配的组。
const myPattern = new URLPattern('https://node.org.cn/docs/latest/api/*.html');
console.log(myPattern.exec('https://node.org.cn/docs/latest/api/dns.html'));
// Prints:
// {
// "hash": { "groups": { "0": "" }, "input": "" },
// "hostname": { "groups": {}, "input": "nodejs.org" },
// "inputs": [
// "https://node.org.cn/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])#
input<string> | <Object> 一个 URL 或 URL 的部分baseURL<string> | <undefined> 一个基础 URL 字符串
输入可以是一个字符串或一个提供各个 URL 部分的对象。对象成员可以是 protocol、username、password、hostname、port、pathname、search、hash 或 baseURL 中的任意一个。
如果未指定 baseURL,则默认为 undefined。
返回一个布尔值,表示输入是否与当前模式匹配。
const myPattern = new URLPattern('https://node.org.cn/docs/latest/api/*.html');
console.log(myPattern.test('https://node.org.cn/docs/latest/api/dns.html'));
// Prints: true
类:URLSearchParams#
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'));
// 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 对象。
new URLSearchParams(string)#
string<string> 一个查询字符串
将 string 解析为查询字符串,并用它来实例化一个新的 URLSearchParams 对象。如果存在前导 '?',则会被忽略。
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 的每个属性的键和值总是被强制转换为字符串。
与 querystring 模块不同,不允许以数组值的形式出现重复的键。数组使用 array.toString() 进行字符串化,它只是用逗号连接所有数组元素。
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 的元素是键值对,并且它们本身也可以是任何可迭代对象。
允许重复的键。
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.delete(name[, value])#
如果提供了 value,则删除所有名称为 name 且值为 value 的名称-值对。
如果未提供 value,则删除所有名称为 name 的名称-值对。
urlSearchParams.entries()#
- 返回:<Iterator>
返回一个 ES6 Iterator,用于遍历查询中的每个名称-值对。迭代器的每个项目都是一个 JavaScript Array。Array 的第一项是 name,第二项是 value。
urlSearchParams.forEach(fn[, thisArg])#
fn<Function> 为查询中的每个名称-值对调用thisArg<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);
});
// Prints:
// a b true
// c d true
urlSearchParams.get(name)#
返回第一个名称为 name 的名称-值对的值。如果没有这样的对,则返回 null。
urlSearchParams.has(name[, value])#
根据 name 和可选的 value 参数,检查 URLSearchParams 对象是否包含键值对。
如果提供了 value,当存在具有相同 name 和 value 的名称-值对时返回 true。
如果未提供 value,只要存在至少一个名称为 name 的名称-值对,就返回 true。
urlSearchParams.keys()#
- 返回:<Iterator>
返回一个 ES6 Iterator,用于遍历每个名称-值对的名称。
const params = new URLSearchParams('foo=bar&foo=baz');
for (const name of params.keys()) {
console.log(name);
}
// Prints:
// foo
// foo
urlSearchParams.set(name, value)#
将 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());
// 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#
参数条目的总数。
urlSearchParams.sort()#
按名称对所有现有的名称-值对进行原地排序。排序使用稳定排序算法完成,因此保留了具有相同名称的名称-值对之间的相对顺序。
此方法尤其可用于增加缓存命中率。
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[Symbol.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);
}
// Prints:
// foo bar
// xyz baz
url.domainToASCII(domain)#
返回 domain 的 Punycode ASCII 序列化。如果 domain 是一个无效的域,则返回空字符串。
它执行与 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 是一个无效的域,则返回空字符串。
它执行与 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[, options])#
url<URL> | <string> 要转换为路径的文件 URL 字符串或 URL 对象。options<Object>windows<boolean> | <undefined> 如果path应作为 Windows 文件路径返回,则为true;对于 Posix,则为false;对于系统默认值,则为undefined。默认值:undefined。
- 返回:<string> 完全解析的平台特定的 Node.js 文件路径。
此函数确保对百分号编码的字符进行正确解码,并确保跨平台有效的绝对路径字符串。
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.fileURLToPathBuffer(url[, options])#
url<URL> | <string> 要转换为路径的文件 URL 字符串或 URL 对象。options<Object>windows<boolean> | <undefined> 如果path应作为 Windows 文件路径返回,则为true;对于 Posix,则为false;对于系统默认值,则为undefined。默认值:undefined。
- 返回:<Buffer> 完全解析的、平台特定的 Node.js 文件路径,作为 <Buffer>。
与 url.fileURLToPath(...) 类似,但它返回的是路径的 Buffer 表示,而不是字符串表示。当输入 URL 包含不是有效 UTF-8 / Unicode 序列的百分号编码段时,这种转换很有用。
url.format(URL[, options])#
URL<URL> 一个 WHATWG URL 对象options<Object>- 返回: <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'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[, options])#
path<string> 要转换为文件 URL 的路径。options<Object>windows<boolean> | <undefined> 如果path应被视为 Windows 文件路径,则为true;对于 Posix,则为false;对于系统默认值,则为undefined。默认值:undefined。
- 返回:<URL> 文件 URL 对象。
此函数确保 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)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 所期望的普通选项对象。
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#
旧版 urlObject#
旧版 urlObject (require('node:url').Url 或 import { Url } from 'node:url') 由 url.parse() 函数创建并返回。
urlObject.auth#
auth 属性是 URL 的用户名和密码部分,也称为用户信息。此字符串子集跟在 protocol 和双斜杠(如果存在)之后,并位于 host 组件之前,由 @ 分隔。该字符串要么是用户名,要么是由 : 分隔的用户名和密码。
例如:'user:pass'。
urlObject.href#
href 属性是解析后的完整 URL 字符串,其中 protocol 和 host 组件都已转换为小写。
例如:'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'。
urlObject.pathname#
pathname 属性包含 URL 的整个路径部分。这是跟在 host(包括 port)之后,并在 query 或 hash 组件开始之前的所有内容,由 ASCII 问号 (?) 或井号 (#) 字符分隔。
例如:'/p/a/t/h'。
不对路径字符串进行解码。
urlObject.query#
query 属性要么是不带前导 ASCII 问号 (?) 的查询字符串,要么是由 querystring 模块的 parse() 方法返回的对象。query 属性是字符串还是对象由传递给 url.parse() 的 parseQueryString 参数决定。
例如:'query=string' 或 {'query': 'string'}。
如果作为字符串返回,则不对查询字符串进行解码。如果作为对象返回,则对键和值都进行解码。
urlObject.search#
search 属性包含 URL 的整个“查询字符串”部分,包括前导的 ASCII 问号 (?) 字符。
例如:'?query=string'。
不对查询字符串进行解码。
urlObject.slashes#
如果 protocol 中的冒号后需要两个 ASCII 正斜杠字符 (/),则 slashes 属性是一个值为 true 的 boolean。
url.format(urlObject)#
urlObject<Object> | <string> 一个 URL 对象(由url.parse()返回或以其他方式构造)。如果是一个字符串,则通过传递给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。 - 如果以下任一条件为真,则字面字符串
//将被追加到resulturlObject.slashes属性为真;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。
url.parse(urlString[, parseQueryString[, slashesDenoteHost]])#
urlString<string> 要解析的 URL 字符串。parseQueryString<boolean> 如果为true,query属性将始终设置为由querystring模块的parse()方法返回的对象。如果为false,返回的 URL 对象上的query属性将是一个未解析、未解码的字符串。默认值:false。slashesDenoteHost<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 || '/'}`);
}
url.resolve(from, to)#
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'
要使用 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 中的百分号编码#
URL 只允许包含特定范围的字符。任何超出该范围的字符都必须进行编码。如何对此类字符进行编码,以及对哪些字符进行编码,完全取决于该字符在 URL 结构中的位置。
旧版 API#
在旧版 API 中,空格 (' ') 和以下字符将在 URL 对象的属性中自动转义:
< > " ` \r \n \t { } | \ ^ '
例如,ASCII 空格字符 (' ') 被编码为 %20。ASCII 正斜杠 (/) 字符被编码为 %3C。
WHATWG API#
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 (})。
-
用户信息编码集包括路径百分号编码集以及码点 U+002F (/)、U+003A (:)、U+003B (;)、U+003D (=)、U+0040 (@)、U+005B ([) 到 U+005E(^) 和 U+007C (|)。
用户信息百分号编码集专门用于在 URL 内编码的用户名和密码。路径百分号编码集用于大多数 URL 的路径。片段百分号编码集用于 URL 片段。C0 控制百分号编码集在某些特定条件下用于主机和路径,以及所有其他情况。
当非 ASCII 字符出现在主机名中时,主机会使用 Punycode 算法进行编码。但请注意,主机名可能同时包含 Punycode 编码和百分号编码的字符:
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