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 を操作するための 2 つの API を提供します。1 つは Node.js 固有のレガシー API で、もう 1 つは Web ブラウザで使用されているのと同じ WHATWG URL 標準 を実装した新しい API です。

WHATWG API とレガシー API の比較を以下に示します。URL 'https://user:[email protected]: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:[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 オブジェクトのすべてのプロパティは、オブジェクト自体にデータプロパティとしてではなく、クラスプロトタイプにゲッターとセッターとして実装されます。そのため、レガシー 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。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.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:[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 のポート部分を取得および設定します。

ポート値は、数値、または `0` から `65535` までの範囲(両端を含む)の数値を含む文字列です。指定された `protocol` の `URL` オブジェクトのデフォルトポートに値を設定すると、`port` 値は空文字列(`''`)になります。

ポート値は空文字列にすることができ、その場合ポートはプロトコル/スキームに依存します。

プロトコルポート
"ftp"21
"file"
"http"80
"https"443
"ws"80
"wss"443

ポートに値を割り当てると、値は最初に `toString()` を使用して文字列に変換されます。

その文字列が無効だが数値で始まる場合、先頭の数字が `port` に割り当てられます。数値が上記の範囲外にある場合は無視されます。

const myURL = new URL('https://example.org:8888');
console.log(myURL.port);
// 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 Standard は、少数の 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 Standard によると、特別なプロトコルス キームは `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` のドキュメントを参照してください。

WHATWG 仕様では、`URLSearchParams` オブジェクトはパーセントエンコードする文字を決定するために異なるルールを使用するため、`searchParams` を使用して `URL` を変更する場合は注意が必要です。たとえば、`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)`#

安定性: 1 - 実験的

指定された <Blob> オブジェクトを表し、後で `Blob` を取得するために使用できる `'blob:nodedata:...'` URL 文字列を作成します。

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` オブジェクトは現在のスレッド内に登録されます。ワーカースレッドを使用する場合、1 つのワーカー内に登録された `Blob` オブジェクトは、他のワーカーまたはメインスレッドでは使用できません。

`URL.revokeObjectURL(id)`#

安定性: 1 - 実験的

  • `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。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` クラスは、次の 4 つのコンストラクタのいずれかを使用してスタンドアロンでも使用できます。`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> 要素がキーと値のペアである反復可能オブジェクト

`Map` のコンストラクタと同様の方法で、反復可能なマップを使用して新しい `URLSearchParams` オブジェクトをインスタンス化します。`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 `Array` です。`Array` の最初の項目は `name` で、`Array` の 2 番目の項目は `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` <string>
  • 戻り値: <string> | <null> 文字列、または指定された`name`を持つ名前と値のペアがない場合は`null`。

名前が`name`である最初の名前と値のペアの値を返します。そのようなペアがない場合は、`null`が返されます。

urlSearchParams.getAll(name)#

名前が`name`であるすべての名前と値のペアの値を返します。そのようなペアがない場合は、空の配列が返されます。

urlSearchParams.has(name[, value])#

`URLSearchParams`オブジェクトに、`name`とオプションの`value`引数に基づくキーと値のペアが含まれているかどうかを確認します。

`value`が指定されている場合、同じ`name`と`value`を持つ名前と値のペアが存在するときに`true`を返します。

`value`が指定されていない場合、名前が`name`である名前と値のペアが少なくとも1つ存在する場合に`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 `Array`です。`Array`の最初の項目は`name`、`Array`の2番目の項目は`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)#

  • url <URL> | <string> パスに変換するファイルURL文字列またはURLオブジェクト。
  • 戻り値: <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.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オブジェクトには、URLの文字列シリアル化を返す`toString()`メソッドと`href`プロパティの両方があります。ただし、これらはカスタマイズできません。 `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)#

  • path <string> ファイルURLに変換するパス。
  • 戻り値: <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> ベーシック認証、つまりAuthorizationヘッダーを計算するための`'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#

安定性: 3 - レガシー: 代わりにWHATWG URL APIを使用してください。

レガシー`urlObject` #

安定性: 3 - レガシー: 代わりにWHATWG URL APIを使用してください。

レガシー`urlObject`(`require('node:url').Url`または`import { Url } from 'node:url'`)は、`url.parse()`関数によって作成され、返されます。

urlObject.auth#

`auth`プロパティは、URLのユーザー名とパスワードの部分であり、_userinfo_とも呼ばれます。この文字列のサブセットは、`protocol`とダブルスラッシュ(存在する場合)の後に続き、`host`コンポーネントの前にあり、`@`で区切られます。文字列はユーザー名のみ、またはユーザー名とパスワードを`:`で区切ったものです。

例:`'user:pass'`。

urlObject.hash#

`hash`プロパティは、先頭の`#`文字を含むURLのフラグメント識別子部分です。

例:`'#hash'`。

urlObject.host#

`host`プロパティは、`port`が指定されている場合はそれも含む、URLの完全な小文字のホスト部分です。

例:`'sub.example.com:8080'`。

urlObject.hostname#

hostname プロパティは、host コンポーネントのホスト名部分を小文字にしたもので、port は含まれません。

例: 'sub.example.com'.

urlObject.href#

href プロパティは、解析された完全な URL 文字列で、protocolhost コンポーネントは小文字に変換されます。

例: 'http://user:[email protected]:8080/p/a/t/h?query=string#hash'.

urlObject.path#

path プロパティは、pathnamesearch コンポーネントを連結したものです。

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

path のデコードは実行されません。

urlObject.pathname#

pathname プロパティは、URL のパスセクション全体で構成されます。これは、hostport を含む)の後から、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 プロパティは、先頭の ASCII の疑問符(?)文字を含む、URL の「クエリ文字列」部分全体で構成されます。

例: '?query=string'.

クエリ文字列のデコードは実行されません。

urlObject.slashes#

slashes プロパティは、protocol のコロンの後に 2 つの ASCII スラッシュ文字(/)が必要な場合、値が true になるブール値です。

url.format(urlObject)#

安定性: 3 - レガシー: 代わりにWHATWG URL APIを使用してください。

  • 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.protocolundefined ではなく、文字列でもない場合、Error がスローされます。
  • ASCII コロン(:)文字で *終わらない* urlObject.protocol のすべての文字列値について、リテラル文字列 :result に追加されます。
  • 次のいずれかの条件が true の場合、リテラル文字列 //result に追加されます
    • urlObject.slashes プロパティが true である。
    • urlObject.protocolhttphttpsftpgopher、または file で始まる。
  • urlObject.auth プロパティの値が truthy で、urlObject.host または urlObject.hostnameundefined でない場合、urlObject.auth の値は文字列に強制変換され、リテラル文字列 @ が後に続いて result に追加されます。
  • urlObject.host プロパティが undefined の場合
    • urlObject.hostname が文字列の場合、result に追加されます。
    • それ以外の場合、urlObject.hostnameundefined ではなく、文字列でもない場合、Error がスローされます。
    • urlObject.port プロパティ値が truthy で、urlObject.hostnameundefined でない場合
      • リテラル文字列 :result に追加され、
      • urlObject.port の値は文字列に強制変換され、result に追加されます。
  • それ以外の場合、urlObject.host プロパティ値が truthy の場合、urlObject.host の値は文字列に強制変換され、result に追加されます。
  • urlObject.pathname プロパティが空の文字列ではない文字列の場合
    • urlObject.pathname が ASCII スラッシュ(/)で *始まらない* 場合、リテラル文字列 '/'result に追加されます。
    • urlObject.pathname の値が result に追加されます。
  • それ以外の場合、urlObject.pathnameundefined ではなく、文字列でもない場合、Error がスローされます。
  • urlObject.search プロパティが undefined で、urlObject.query プロパティが Object の場合、リテラル文字列 ?result に追加され、その後に urlObject.query の値を渡して querystring モジュールの stringify() メソッドを呼び出した出力が続きます。
  • それ以外の場合、urlObject.search が文字列の場合
    • urlObject.search の値が ASCII の疑問符(?)文字で *始まらない* 場合、リテラル文字列 ?result に追加されます。
    • urlObject.search の値が result に追加されます。
  • それ以外の場合、urlObject.searchundefined ではなく、文字列でもない場合、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> true の場合、query プロパティは常に querystring モジュールの parse() メソッドによって返されるオブジェクトに設定されます。 false の場合、返された URL オブジェクトの query プロパティは、解析およびデコードされていない文字列になります。 **デフォルト:** false.
  • slashesDenoteHost <boolean> true の場合、リテラル文字列 // の後、次の / の前にある最初のトークンは host として解釈されます。たとえば、//foo/bar が指定された場合、結果は {pathname: '//foo/bar'} ではなく {host: 'foo', pathname: '/bar'} になります。 **デフォルト:** false.

url.parse() メソッドは、URL 文字列を受け取り、解析し、URL オブジェクトを返します。

urlString が文字列でない場合、TypeError がスローされます。

auth プロパティが存在するがデコードできない場合、URIError がスローされます。

url.parse() は、URL 文字列の解析に、寛容で非標準のアルゴリズムを使用します。 ホスト名スプーフィング やユーザー名とパスワードの誤った処理などのセキュリティ問題が発生しやすいため、信頼できない入力には使用しないでください。 url.parse() の脆弱性に対して CVE は発行されません。代わりに WHATWG URL API を使用してください。

url.resolve(from, to)#

安定性: 3 - レガシー: 代わりにWHATWG URL APIを使用してください。

  • from <string> to が相対 URL の場合に使用されるベース URL。
  • to <string> 解決するターゲット URL。

url.resolve() メソッドは、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 スラッシュ(/)文字は %2F としてエンコードされます。(原文に誤りがありましたので修正しました)

WHATWG API#

WHATWG URL 標準 は、レガシー API で使用されるよりも、エンコードされた文字を選択するための、より選択的で詳細なアプローチを使用します。

WHATWG アルゴリズムは、パーセントエンコードする必要がある文字の範囲を記述する 4 つの「パーセントエンコードセット」を定義しています

  • 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