URL#

穩定性:2 - 穩定

原始碼: 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 屬性包括 protocolhost,但不包括 usernamepassword

┌────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                              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.protocoldelete 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'.

如果 inputbase 不是有效的 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#

獲取並設定 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#

獲取並設定 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#

獲取並設定 URL 的主機名部分。url.hosturl.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#

獲取並設定序列化的 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#

獲取 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#

獲取並設定 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#

獲取並設定 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#

獲取並設定 URL 的埠部分。

埠值可以是一個數字或一個包含數字的字串,範圍在 065535(含)之間。將值設定為 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#

獲取並設定 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 標準,特殊協議方案是 ftpfilehttphttpswswss

url.search#

獲取並設定 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#

獲取並設定 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.toString()#

URL 物件上的 toString() 方法返回序列化的 URL。返回的值等同於 url.hrefurl.toJSON() 的值。

url.toJSON()#

URL 物件上的 toJSON() 方法返回序列化的 URL。返回的值等同於 url.hrefurl.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>

檢查相對於 baseinput 是否可以解析為 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#

穩定性:1 - 實驗性

URLPattern API 提供了一個介面,用於將 URL 或 URL 的一部分與模式進行匹配。

const myPattern = new URLPattern('https://nodejs.com.tw/docs/latest/api/*.html');
console.log(myPattern.exec('https://nodejs.com.tw/docs/latest/api/dns.html'));
// Prints:
// {
//  "hash": { "groups": {  "0": "" },  "input": "" },
//  "hostname": { "groups": {}, "input": "nodejs.org" },
//  "inputs": [
//    "https://nodejs.com.tw/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.com.tw/docs/latest/api/dns.html'));
// Prints: true 
new URLPattern()#

例項化一個新的空 URLPattern 物件。

new URLPattern(string[, baseURL][, options])#

string 解析為 URL,並用它來例項化一個新的 URLPattern 物件。

如果未指定 baseURL,則預設為 undefined

選項可以有一個 ignoreCase 布林屬性,如果設定為 true,則啟用不區分大小寫的匹配。

建構函式可能會丟擲一個 TypeError 來表示解析失敗。

new URLPattern(obj[, baseURL][, options])#

Object 解析為輸入模式,並用它來例項化一個新的 URLPattern 物件。該物件的成員可以是 protocolusernamepasswordhostnameportpathnamesearchhashbaseURL 中的任意一個。

如果未指定 baseURL,則預設為 undefined

選項可以有一個 ignoreCase 布林屬性,如果設定為 true,則啟用不區分大小寫的匹配。

建構函式可能會丟擲一個 TypeError 來表示解析失敗。

urlPattern.exec(input[, baseURL])#

輸入可以是一個字串或一個提供各個 URL 部分的物件。物件成員可以是 protocolusernamepasswordhostnameportpathnamesearchhashbaseURL 中的任意一個。

如果未指定 baseURL,則預設為 undefined

返回一個物件,其中包含一個 inputs 鍵,其值為傳入函式的引數陣列,以及 URL 元件的鍵,其中包含匹配的輸入和匹配的組。

const myPattern = new URLPattern('https://nodejs.com.tw/docs/latest/api/*.html');
console.log(myPattern.exec('https://nodejs.com.tw/docs/latest/api/dns.html'));
// Prints:
// {
//  "hash": { "groups": {  "0": "" },  "input": "" },
//  "hostname": { "groups": {}, "input": "nodejs.org" },
//  "inputs": [
//    "https://nodejs.com.tw/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])#

輸入可以是一個字串或一個提供各個 URL 部分的物件。物件成員可以是 protocolusernamepasswordhostnameportpathnamesearchhashbaseURL 中的任意一個。

如果未指定 baseURL,則預設為 undefined

返回一個布林值,表示輸入是否與當前模式匹配。

const myPattern = new URLPattern('https://nodejs.com.tw/docs/latest/api/*.html');
console.log(myPattern.test('https://nodejs.com.tw/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 解析為查詢字串,並用它來例項化一個新的 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.append(name, value)#

向查詢字串中追加一個新的名稱-值對。

urlSearchParams.delete(name[, value])#

如果提供了 value,則刪除所有名稱為 name 且值為 value 的名稱-值對。

如果未提供 value,則刪除所有名稱為 name 的名稱-值對。

urlSearchParams.entries()#

返回一個 ES6 Iterator,用於遍歷查詢中的每個名稱-值對。迭代器的每個專案都是一個 JavaScript ArrayArray 的第一項是 name,第二項是 value

urlSearchParams[Symbol.iterator]() 的別名。

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 <string>
  • 返回:<string> | <null> 一個字串,如果沒有給定 name 的名稱-值對,則為 null

返回第一個名稱為 name 的名稱-值對的值。如果沒有這樣的對,則返回 null

urlSearchParams.getAll(name)#

返回所有名稱為 name 的名稱-值對的值。如果沒有這樣的對,則返回一個空陣列。

urlSearchParams.has(name[, value])#

根據 name 和可選的 value 引數,檢查 URLSearchParams 物件是否包含鍵值對。

如果提供了 value,當存在具有相同 namevalue 的名稱-值對時返回 true

如果未提供 value,只要存在至少一個名稱為 name 的名稱-值對,就返回 true

urlSearchParams.keys()#

返回一個 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.toString()#

返回序列化為字串的搜尋引數,必要時對字元進行百分號編碼。

urlSearchParams.values()#

返回一個 ES6 Iterator,用於遍歷每個名稱-值對的值。

urlSearchParams[Symbol.iterator]()#

返回一個 ES6 Iterator,用於遍歷查詢字串中的每個名稱-值對。迭代器的每個專案都是一個 JavaScript ArrayArray 的第一項是 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)#

返回 domainPunycode 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>
    • 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 表示的序列化。

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#

穩定性:3 - 舊版:請改用 WHATWG URL API。

舊版 urlObject#

舊版 urlObject (require('node:url').Urlimport { Url } from 'node:url') 由 url.parse() 函式建立並返回。

urlObject.auth#

auth 屬性是 URL 的使用者名稱和密碼部分,也稱為使用者資訊。此字串子集跟在 protocol 和雙斜槓(如果存在)之後,並位於 host 元件之前,由 @ 分隔。該字串要麼是使用者名稱,要麼是由 : 分隔的使用者名稱和密碼。

例如:'user:pass'

urlObject.hash#

hash 屬性是 URL 的片段識別符號部分,包括前導的 # 字元。

例如:'#hash'

urlObject.host#

host 屬性是 URL 的完整小寫主機部分,包括指定的 port

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

urlObject.hostname#

hostname 屬性是 host 元件的小寫主機名部分,包括 port

例如:'sub.example.com'

urlObject.href#

href 屬性是解析後的完整 URL 字串,其中 protocolhost 元件都已轉換為小寫。

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

urlObject.path#

path 屬性是 pathnamesearch 元件的串聯。

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

不對 path 進行解碼。

urlObject.pathname#

pathname 屬性包含 URL 的整個路徑部分。這是跟在 host(包括 port)之後,並在 queryhash 元件開始之前的所有內容,由 ASCII 問號 (?) 或井號 (#) 字元分隔。

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

不對路徑字串進行解碼。

urlObject.port#

port 屬性是 host 元件的數字埠部分。

例如:'8080'

urlObject.protocol#

protocol 屬性標識 URL 的小寫協議方案。

例如:'http:'

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 屬性是一個值為 trueboolean

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
  • 如果以下任一條件為真,則字面字串 // 將被追加到 result
    • urlObject.slashes 屬性為真;
    • 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 物件。

如果 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)#

  • from <string> 如果 to 是相對 URL,則使用的基礎 URL。
  • to <string> 要解析的目標 URL。

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