Node.js v21.7.2 文件
- Node.js v21.7.2
-
► 目錄
- URL
- URL 字串和 URL 物件
- WHATWG URL API
- 類別:
URL
- 類別:
URLSearchParams
new 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.size
urlSearchParams.sort()
urlSearchParams.toString()
urlSearchParams.values()
urlSearchParams[Symbol.iterator]()
url.domainToASCII(domain)
url.domainToUnicode(domain)
url.fileURLToPath(url)
url.format(URL[, options])
url.pathToFileURL(path)
url.urlToHttpOptions(url)
- 類別:
- 舊版 URL API
- URL 中的百分比編碼
- URL
-
► 索引
- 斷言測試
- 非同步內容追蹤
- 非同步掛鉤
- 緩衝區
- C++ 外掛程式
- 使用 Node-API 的 C/C++ 外掛程式
- C++ 內嵌 API
- 子程序
- 叢集
- 命令列選項
- 主控台
- Corepack
- 加密
- 偵錯器
- 已棄用的 API
- 診斷頻道
- DNS
- 網域
- 錯誤
- 事件
- 檔案系統
- 全域變數
- HTTP
- HTTP/2
- HTTPS
- 檢查器
- 國際化
- 模組:CommonJS 模組
- 模組:ECMAScript 模組
- 模組:
node:module
API - 模組:套件
- 網路
- 作業系統
- 路徑
- 效能掛鉤
- 權限
- 程序
- Punycode
- 查詢字串
- Readline
- REPL
- 報告
- 單一可執行應用程式
- 串流
- 字串解碼器
- 測試執行器
- 計時器
- TLS/SSL
- 追蹤事件
- TTY
- UDP/資料包
- URL
- 公用程式
- V8
- VM
- 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,以及一個較新的 API,實作與網頁瀏覽器使用的 WHATWG URL 標準 相同。
以下是 WHATWG 和舊版 API 的比較。在 URL 'https://user:[email protected]: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:[email protected]:8080/p/a/t/h?query=string#hash');
使用舊版 API 解析 URL 字串
import url from 'node:url';
const myURL =
url.parse('https://user:[email protected]:8080/p/a/t/h?query=string#hash');
const url = require('node:url');
const myURL =
url.parse('https://user:[email protected]: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
#
與 WHATWG URL 標準相符的瀏覽器相容 URL
類別。可以在標準本身中找到 已剖析 URL 的範例。URL
類別也可以在全域物件上使用。
根據瀏覽器慣例,URL
物件的所有屬性都實作為類別原型上的 getter 和 setter,而不是作為物件本身的資料屬性。因此,與 舊版 urlObject
不同,對 URL
物件的任何屬性使用 delete
關鍵字(例如 delete myURL.protocol
、delete myURL.pathname
等)都不會產生作用,但仍會傳回 true
。
new URL(input[, base])
#
input
<字串> 要剖析的絕對或相對輸入 URL。如果input
是相對的,則需要base
。如果input
是絕對的,則會忽略base
。如果input
不是字串,則會先將其 轉換為字串。base
<字串> 如果input
不是絕對路徑,則解析為基準的基礎 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
#
取得並設定 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.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
#
取得並設定序列化 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:[email protected]');
console.log(myURL.password);
// Prints xyz
myURL.password = '123';
console.log(myURL.href);
// Prints https://abc:[email protected]/
指定給 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 的 port 部分。
port 的值可以是數字或包含數字的字串,範圍從 0
到 65535
(包含)。將值設定為給定 protocol
的 URL
物件的預設 port,將會導致 port
值變成空字串(''
)。
port 值可以是空字串,這種情況下 port 會取決於 protocol/scheme
protocol | port |
---|---|
"ftp" | 21 |
"file" | |
"http" | 80 |
"https" | 443 |
"ws" | 80 |
"wss" | 443 |
在將值指定給 port 時,該值會先使用 .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 的 port,假設它們有效
myURL.port = 4.567e21;
console.log(myURL.port);
// Prints 4 (because it is the leading number in the string '4.567e21')
url.protocol
#
取得並設定 URL 的 protocol 部分。
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 protocol 值會被忽略。
特殊 scheme#
WHATWG URL 標準 認為少數 URL protocol scheme 在解析和序列化方式上是特殊的。當使用其中一個特殊 protocol 解析 URL 時,url.protocol
屬性可能會變更為另一個特殊 protocol,但不能變更為非特殊 protocol,反之亦然。
例如,從 http
變更為 https
是可行的
const u = new URL('http://example.org');
u.protocol = 'https';
console.log(u.href);
// https://example.org/
但是,從 http
變更為假設的 fish
protocol 是不行的,因為新的 protocol 不是特殊的。
const u = new URL('http://example.org');
u.protocol = 'fish';
console.log(u.href);
// http://example.org/
同樣地,從非特殊 protocol 變更為特殊 protocol 也不被允許
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
#
取得並設定 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:[email protected]');
console.log(myURL.username);
// Prints abc
myURL.username = '123';
console.log(myURL.href);
// Prints https://123:[email protected]/
出現在指派給 username
屬性的值中的任何無效 URL 字元都會 百分比編碼。要百分比編碼哪些字元的選擇可能與 url.parse()
和 url.format()
方法產生的內容略有不同。
url.toString()
#
- 傳回:<字串>
URL
物件上的 toString()
方法傳回序列化後的 URL。傳回的值等同於 url.href
和 url.toJSON()
。
url.toJSON()
#
- 傳回:<字串>
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
物件會在目前的執行緒中註冊。如果使用 Worker Threads,在一個 Worker 中註冊的 Blob
物件將不會提供給其他 worker 或主執行緒。
URL.revokeObjectURL(id)
#
id
<字串> 由先前呼叫URL.createObjectURL()
傳回的'blob:nodedata:...
URL 字串。
移除由給定 ID 識別的已儲存 <Blob>。嘗試撤銷未註冊的 ID 會在無聲的情況下失敗。
URL.canParse(input[, base])
#
input
<字串> 要剖析的絕對或相對輸入 URL。如果input
是相對的,則需要base
。如果input
是絕對的,則會忽略base
。如果input
不是字串,則會先將其 轉換為字串。base
<字串> 如果input
不是絕對路徑,則解析為基準的基礎 URL。如果base
不是字串,則會先 轉換為字串。- 傳回:<boolean>
檢查相對於 base
的 input
是否可以解析為 URL
。
const isValid = URL.canParse('/foo', 'https://example.org/'); // true
const isNotValid = URL.canParse('/foo'); // false
類別: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.append(name, value)
#
將新的名稱值對附加到查詢字串。
urlSearchParams.delete(name[, value])
#
如果提供 value
,則移除所有名稱為 name
且值為 value
的名稱值對。
如果未提供 value
,則移除所有名稱為 name
的名稱值對。
urlSearchParams.entries()
#
- 傳回:<Iterator>
傳回查詢中每個名稱值對的 ES6 Iterator
。迭代器的每個項目都是 JavaScript Array
。Array
的第一個項目是 name
,Array
的第二個項目是 value
。
urlSearchParams[@@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
。如果沒有此類對應,則傳回 null
。
urlSearchParams.getAll(name)
#
name
<string>- 傳回:<string[]>
傳回所有名稱/值對的值,其名稱為 name
。如果沒有此類對應,則傳回空陣列。
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)
#
將與 name
關聯的 URLSearchParams
物件中的值設定為 value
。如果存在任何先前存在的 name-value 成對且其名稱為 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()
#
依據名稱就地排序所有現有的 name-value 成對。排序會使用 穩定排序演算法 進行,因此具有相同名稱的 name-value 成對之間的相對順序會被保留。
這個方法特別可用於增加快取命中次數。
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()
#
- 傳回:<Iterator>
傳回每個 name-value 成對值的 ES6 Iterator
。
urlSearchParams[Symbol.iterator]()
#
- 傳回:<Iterator>
傳回查詢字串中每個 name-value 成對的 ES6 Iterator
。每個 iterator 的項目都是 JavaScript Array
。Array
的第一個項目是 name
,Array
的第二個項目是 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)
#
傳回 Punycode ASCII 序列化 domain
。如果 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 string
const 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 string
const 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)
#
此函式確保正確解碼百分比編碼字元,並確保跨平台有效的絕對路徑字串。
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/
fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows)
new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt
fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows)
new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt
fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX)
new URL('file:///hello world').pathname; // Incorrect: /hello%20world
fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX)
const { fileURLToPath } = require('node:url');
new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/
fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows)
new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt
fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows)
new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt
fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX)
new URL('file:///hello world').pathname; // Incorrect: /hello%20world
fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX)
url.format(URL[, options])
#
URL
<URL> WHATWG URL 物件選項
<Object>- 傳回:<字串>
傳回 WHATWG URL 物件的 URL 字串
表示形式的可自訂序列化。
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)
#
此函式可確保 路徑
絕對解析,且在轉換為檔案 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
<字串> 要使用的通訊協定。hostname
<字串> 要對其發出要求的伺服器的網域名稱或 IP 位址。hash
<字串> URL 的片段部分。search
<字串> URL 的序列化查詢部分。pathname
<字串> URL 的路徑部分。path
<字串> 要求路徑。應包含查詢字串(若有)。例如:'/index.html?page=12'
。當要求路徑包含非法字元時,會擲回例外。目前僅拒絕空白,但這可能會在未來變更。href
<字串> 序列化的 URL。port
<數字> 遠端伺服器的連接埠。auth
<字串> 基本驗證,例如'user:password'
用於計算授權標頭。
此公用程式函式將 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.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 字串,已解析並將 protocol
和 host
組件轉換為小寫。
例如:'http://user:[email protected]:8080/p/a/t/h?query=string#hash'
。
urlObject.path
#
path
屬性是 pathname
和 search
組件的串接。
例如:'/p/a/t/h?query=string'
。
不會對 path
進行任何解碼。
urlObject.pathname
#
pathname
屬性包含 URL 的完整路徑區段。這是 host
(包括 port
) 之後和 query
或 hash
組件開始之前的全部內容,由 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
屬性為值為 true
的 boolean
。
url.format(urlObject)
#
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
。 - 對於
urlObject.protocol
的所有字串值,如果沒有以 ASCII 冒號 (:
) 字元結尾,則會將字面字串:
附加到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
。
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。
url.resolve(from, to)
#
url.resolve()
方法會解析目標 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 空格、U+0022 (")、U+003C (<)、U+003E (>) 和 U+0060 (`)。
-
路徑百分比編碼組 包含 C0 控制百分比編碼組 和碼點 U+0020 空格、U+0022 (")、U+0023 (#)、U+003C (<)、U+003E (>)、U+003F (?)、U+0060 (`)、U+007B ({) 和 U+007D (})。
-
使用者資訊編碼組 包含 路徑百分比編碼組 和碼點 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