温馨提示:本站仅提供公开网络链接索引服务,不存储、不篡改任何第三方内容,所有内容版权归原作者所有
AI智能索引来源:http://www.bun.com/reference/node/url
点击访问原文链接

Node.js url module | API Reference | Bun

Node.js url module | API Reference | BunBuildDocsReferenceGuidesBlogDiscord/node:urlFdomainToASCIIFdomainToUnicodeFfileURLToPathFfileURLToPathBufferFformatFparseFpathToFileURLFresolveCURLPatternFurlToHttpOptions

Search the reference...

/

BuildDocsReferenceGuidesBlogDiscord/node:urlFdomainToASCIIFdomainToUnicodeFfileURLToPathFfileURLToPathBufferFformatFparseFpathToFileURLFresolveCURLPatternFurlToHttpOptions

Node.js module

url

The 'node:url' module provides utilities to parse, format, and resolve URLs. It includes the URL and URLSearchParams classes that conform to the WHATWG URL specification.

Features include protocol, hostname, pathname, query string parsing, and manipulation, allowing robust URL handling in network applications.

Works in Bun

Fully implemented.

const URL: new (url: string | URL, base?: string | URL) => URLconst URLSearchParams: new (init?: string | string[][] | URLSearchParams | Recordstring, string>) => URLSearchParamsfunction domainToASCII(domain: string): string;

Returns the Punycode ASCII serialization of the domain. If domain is an invalid domain, the empty string is returned.

It performs the inverse operation to 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
function domainToUnicode(domain: string): string;

Returns the Unicode serialization of the domain. If domain is an invalid domain, the empty string is returned.

It performs the inverse operation to 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
function fileURLToPath(url: string | URL,options?: FileUrlToPathOptions): string;

This function ensures the correct decodings of percent-encoded characters as well as ensuring a cross-platform valid absolute path string.

import { fileURLToPath } from 'node:url';

const __filename = fileURLToPath(import.meta.url);

new URL('file:http:///C:/path/').pathname; // Incorrect: /C:/path/
fileURLToPath('file:http:///C:/path/'); // Correct: C:\path\ (Windows)

new URL('file:http://nas/foo.txt').pathname; // Incorrect: /foo.txt
fileURLToPath('file:http://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows)

new URL('file:http:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt
fileURLToPath('file:http:///你好.txt'); // Correct: /你好.txt (POSIX)

new URL('file:http:///hello world').pathname; // Incorrect: /hello%20world
fileURLToPath('file:http:///hello world'); // Correct: /hello world (POSIX)

Security Considerations:

This function decodes percent-encoded characters, including encoded dot-segments (%2e as . and %2e%2e as ..), and then normalizes the resulting path. This means that encoded directory traversal sequences (such as %2e%2e) are decoded and processed as actual path traversal, even though encoded slashes (%2F, %5C) are correctly rejected.

Applications must not rely on fileURLToPath() alone to prevent directory traversal attacks. Always perform explicit path validation and security checks on the returned path value to ensure it remains within expected boundaries before using it for file system operations.

@param url

The file URL string or URL object to convert to a path.

@returns

The fully-resolved platform-specific Node.js file path.

function fileURLToPathBuffer(url: string | URL,options?: FileUrlToPathOptions): NonSharedBuffer;

Like url.fileURLToPath(...) except that instead of returning a string representation of the path, a Buffer is returned. This conversion is helpful when the input URL contains percent-encoded segments that are not valid UTF-8 / Unicode sequences.

Security Considerations:

This function has the same security considerations as url.fileURLToPath(). It decodes percent-encoded characters, including encoded dot-segments (%2e as . and %2e%2e as ..), and normalizes the path. Applications must not rely on this function alone to prevent directory traversal attacks. Always perform explicit path validation on the returned buffer value before using it for file system operations.

@param url

The file URL string or URL object to convert to a path.

@returns

The fully-resolved platform-specific Node.js file path as a Buffer.

'https://example.com/some/path?page=1&format=json' ``` If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. The formatting process operates as follows: * A new empty string `result` is created. * If `urlObject.protocol` is a string, it is appended as-is to `result`. * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. * For all string values of `urlObject.protocol` that _do not end_ with an ASCII colon (`:`) character, the literal string `:` will be appended to `result`. * If either of the following conditions is true, then the literal string `http://` will be appended to `result`: * `urlObject.slashes` property is true; * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or `file`; * If the value of the `urlObject.auth` property is truthy, and either `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of `urlObject.auth` will be coerced into a string and appended to `result` followed by the literal string `@`. * If the `urlObject.host` property is `undefined` then: * If the `urlObject.hostname` is a string, it is appended to `result`. * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, an `Error` is thrown. * If the `urlObject.port` property value is truthy, and `urlObject.hostname` is not `undefined`: * The literal string `:` is appended to `result`, and * The value of `urlObject.port` is coerced to a string and appended to `result`. * Otherwise, if the `urlObject.host` property value is truthy, the value of `urlObject.host` is coerced to a string and appended to `result`. * If the `urlObject.pathname` property is a string that is not an empty string: * If the `urlObject.pathname` _does not start_ with an ASCII forward slash (`/`), then the literal string `'/'` is appended to `result`. * The value of `urlObject.pathname` is appended to `result`. * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result` followed by the output of calling the `querystring` module's `stringify()` method passing the value of `urlObject.query`. * Otherwise, if `urlObject.search` is a string: * If the value of `urlObject.search` _does not start_ with the ASCII question mark (`?`) character, the literal string `?` is appended to `result`. * The value of `urlObject.search` is appended to `result`. * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. * If the `urlObject.hash` property is a string: * If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`) character, the literal string `#` is appended to `result`. * The value of `urlObject.hash` is appended to `result`. * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a string, an `Error` is thrown. * `result` is returned." data-algolia-static="false" data-algolia-merged="false" data-type="Function">function format(urlObject: URL,options?: URLFormatOptions): string;

The url.format() method returns a formatted URL string derived from urlObject.

import url from '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'

If urlObject is not an object or a string, url.format() will throw a TypeError.

The formatting process operates as follows:

A new empty string result is created.If urlObject.protocol is a string, it is appended as-is to result.Otherwise, if urlObject.protocol is not undefined and is not a string, an Error is thrown.For all string values of urlObject.protocol that do not end with an ASCII colon (:) character, the literal string : will be appended to result.If either of the following conditions is true, then the literal string http:// will be appended to result:urlObject.slashes property is true;urlObject.protocol begins with http, https, ftp, gopher, or file;If the value of the urlObject.auth property is truthy, and either urlObject.host or urlObject.hostname are not undefined, the value of urlObject.auth will be coerced into a string and appended to result followed by the literal string @.If the urlObject.host property is undefined then:If the urlObject.hostname is a string, it is appended to result.Otherwise, if urlObject.hostname is not undefined and is not a string, an Error is thrown.If the urlObject.port property value is truthy, and urlObject.hostname is not undefined: * The literal string : is appended to result, and * The value of urlObject.port is coerced to a string and appended to result.Otherwise, if the urlObject.host property value is truthy, the value of urlObject.host is coerced to a string and appended to result.If the urlObject.pathname property is a string that is not an empty string:If the urlObject.pathname does not start with an ASCII forward slash (/), then the literal string '/' is appended to result.The value of urlObject.pathname is appended to result.Otherwise, if urlObject.pathname is not undefined and is not a string, an Error is thrown.If the urlObject.search property is undefined and if the urlObject.queryproperty is an Object, the literal string ? is appended to result followed by the output of calling the querystring module's stringify() method passing the value of urlObject.query.Otherwise, if urlObject.search is a string:If the value of urlObject.search does not start with the ASCII question mark (?) character, the literal string ? is appended to result.The value of urlObject.search is appended to result.Otherwise, if urlObject.search is not undefined and is not a string, an Error is thrown.If the urlObject.hash property is a string:If the value of urlObject.hash does not start with the ASCII hash (#) character, the literal string # is appended to result.The value of urlObject.hash is appended to result.Otherwise, if the urlObject.hash property is not undefined and is not a string, an Error is thrown.result is returned.
@param urlObject

A URL object (as returned by url.parse() or constructed otherwise). If a string, it is converted to an object by passing it to url.parse().

function format(urlObject: UrlObject): string;

The url.format() method returns a formatted URL string derived from urlObject.

import url from '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'

If urlObject is not an object or a string, url.format() will throw a TypeError.

The formatting process operates as follows:

A new empty string result is created.If urlObject.protocol is a string, it is appended as-is to result.Otherwise, if urlObject.protocol is not undefined and is not a string, an Error is thrown.For all string values of urlObject.protocol that do not end with an ASCII colon (:) character, the literal string : will be appended to result.If either of the following conditions is true, then the literal string http:// will be appended to result:urlObject.slashes property is true;urlObject.protocol begins with http, https, ftp, gopher, or file;If the value of the urlObject.auth property is truthy, and either urlObject.host or urlObject.hostname are not undefined, the value of urlObject.auth will be coerced into a string and appended to result followed by the literal string @.If the urlObject.host property is undefined then:If the urlObject.hostname is a string, it is appended to result.Otherwise, if urlObject.hostname is not undefined and is not a string, an Error is thrown.If the urlObject.port property value is truthy, and urlObject.hostname is not undefined: * The literal string : is appended to result, and * The value of urlObject.port is coerced to a string and appended to result.Otherwise, if the urlObject.host property value is truthy, the value of urlObject.host is coerced to a string and appended to result.If the urlObject.pathname property is a string that is not an empty string:If the urlObject.pathname does not start with an ASCII forward slash (/), then the literal string '/' is appended to result.The value of urlObject.pathname is appended to result.Otherwise, if urlObject.pathname is not undefined and is not a string, an Error is thrown.If the urlObject.search property is undefined and if the urlObject.queryproperty is an Object, the literal string ? is appended to result followed by the output of calling the querystring module's stringify() method passing the value of urlObject.query.Otherwise, if urlObject.search is a string:If the value of urlObject.search does not start with the ASCII question mark (?) character, the literal string ? is appended to result.The value of urlObject.search is appended to result.Otherwise, if urlObject.search is not undefined and is not a string, an Error is thrown.If the urlObject.hash property is a string:If the value of urlObject.hash does not start with the ASCII hash (#) character, the literal string # is appended to result.The value of urlObject.hash is appended to result.Otherwise, if the urlObject.hash property is not undefined and is not a string, an Error is thrown.result is returned.
@param urlObject

A URL object (as returned by url.parse() or constructed otherwise).

function pathToFileURL(path: string,options?: PathToFileUrlOptions): URL;

This function ensures that path is resolved absolutely, and that the URL control characters are correctly encoded when converting into a File URL.

import { pathToFileURL } from 'node:url';

new URL('/foo#1', 'file:'); // Incorrect: file:http:///foo#1
pathToFileURL('/foo#1'); // Correct: file:http:///foo%231 (POSIX)

new URL('/some/path%.c', 'file:'); // Incorrect: file:http:///some/path%.c
pathToFileURL('/some/path%.c'); // Correct: file:http:///some/path%25.c (POSIX)
@param path

The path to convert to a File URL.

@returns

The file URL object.

function urlToHttpOptions(url: URL): ClientRequestArgs;

This utility function converts a URL object into an ordinary options object as expected by the http.request() and https.request() APIs.

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'
}

@param url

The WHATWG URL object to convert to an options object.

@returns

Options object

class URLPatternreadonly hash: stringreadonly hasRegExpGroups: booleanreadonly hostname: stringreadonly password: stringreadonly pathname: stringreadonly port: stringreadonly protocol: stringreadonly search: stringreadonly username: stringexec(input?: URLPatternInput,baseURL?: string | URL): null | URLPatternResult;test(input?: URLPatternInput,baseURL?: string | URL): boolean;Type definitionsinterface FileUrlToPathOptionswindows?: boolean

true if the path should be return as a windows filepath, false for posix, and undefined for the system default.

interface PathToFileUrlOptionswindows?: boolean

true if the path should be return as a windows filepath, false for posix, and undefined for the system default.

interface Urlauth: null | stringhash: null | stringhost: null | stringhostname: null | stringhref: stringpath: null | stringpathname: null | stringport: null | stringprotocol: null | stringquery: null | string | ParsedUrlQuerysearch: null | stringslashes: null | booleaninterface URLhash: stringhost: stringhostname: stringhref: stringreadonly origin: stringpassword: stringpathname: stringport: stringprotocol: stringsearch: stringreadonly searchParams: URLSearchParamsusername: stringtoJSON(): string;interface URLFormatOptionsauth?: boolean

true if the serialized URL string should include the username and password, false otherwise.

fragment?: boolean

true if the serialized URL string should include the fragment, false otherwise.

search?: boolean

true if the serialized URL string should include the search query, false otherwise.

unicode?: boolean

true if Unicode characters appearing in the host component of the URL string should be encoded directly as opposed to being Punycode encoded.

interface UrlObjectauth?: null | stringhash?: null | stringhost?: null | stringhostname?: null | stringhref?: null | stringpathname?: null | stringport?: null | string | numberprotocol?: null | stringquery?: null | string | ParsedUrlQueryInputsearch?: null | stringslashes?: null | booleaninterface URLPatternComponentResultgroups: Recordstring, undefined | string>input: stringinterface URLPatternInitbaseURL?: stringhash?: stringhostname?: stringpassword?: stringpathname?: stringport?: stringprotocol?: stringsearch?: stringusername?: stringinterface URLPatternOptionsignoreCase?: booleaninterface URLPatternResulthash: URLPatternComponentResulthostname: URLPatternComponentResultinputs: URLPatternInput[]password: URLPatternComponentResultpathname: URLPatternComponentResultport: URLPatternComponentResultprotocol: URLPatternComponentResultsearch: URLPatternComponentResultusername: URLPatternComponentResultinterface URLSearchParamsreadonly size: numberappend(name: string,value: string): void;delete(name: string,value?: string): void;entries(): URLSearchParamsIterator[string, string]>;forEach(callbackfn: (value: string, key: string, parent: URLSearchParams) => void,thisArg?: any): void;get(name: string): null | string;getAll(name: string): string[];has(name: string,value?: string): boolean;keys(): URLSearchParamsIteratorstring>;set(name: string,value: string): void;sort(): void;values(): URLSearchParamsIteratorstring>;interface URLSearchParamsIteratorT>readonly [Symbol.toStringTag]: string[Symbol.dispose](): void;[Symbol.iterator](): URLSearchParamsIteratorT>;drop(count: number): IteratorObjectT, undefined, unknown>;

Creates an iterator whose values are the values from this iterator after skipping the provided count.

@param count

The number of values to drop.

every(predicate: (value: T, index: number) => unknown): boolean;

Determines whether all the members of this iterator satisfy the specified test.

@param predicate

A function that accepts up to two arguments. The every method calls the predicate function for each element in this iterator until the predicate returns false, or until the end of this iterator.

filterS>(predicate: (value: T, index: number) => value is S): IteratorObjectS, undefined, unknown>;

Creates an iterator whose values are those from this iterator for which the provided predicate returns true.

@param predicate

A function that accepts up to two arguments to be used to test values from the underlying iterator.

filter(predicate: (value: T, index: number) => unknown): IteratorObjectT, undefined, unknown>;

Creates an iterator whose values are those from this iterator for which the provided predicate returns true.

@param predicate

A function that accepts up to two arguments to be used to test values from the underlying iterator.

findS>(predicate: (value: T, index: number) => value is S): undefined | S;

Returns the value of the first element in this iterator where predicate is true, and undefined otherwise.

@param predicate

find calls predicate once for each element of this iterator, in order, until it finds one where predicate returns true. If such an element is found, find immediately returns that element value. Otherwise, find returns undefined.

find(predicate: (value: T, index: number) => unknown): undefined | T;flatMapU>(callback: (value: T, index: number) => IteratorU, unknown, undefined> | IterableU, unknown, undefined>): IteratorObjectU, undefined, unknown>;

Creates an iterator whose values are the result of applying the callback to the values from this iterator and then flattening the resulting iterators or iterables.

@param callback

A function that accepts up to two arguments to be used to transform values from the underlying iterator into new iterators or iterables to be flattened into the result.

forEach(callbackfn: (value: T, index: number) => void): void;

Performs the specified action for each element in the iterator.

@param callbackfn

A function that accepts up to two arguments. forEach calls the callbackfn function one time for each element in the iterator.

mapU>(callbackfn: (value: T, index: number) => U): IteratorObjectU, undefined, unknown>;

Creates an iterator whose values are the result of applying the callback to the values from this iterator.

@param callbackfn

A function that accepts up to two arguments to be used to transform values from the underlying iterator.

next(...__namedParameters: [] | [unknown]): IteratorResultT, undefined>;reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number) => T): T;

Calls the specified callback function for all the elements in this iterator. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

@param callbackfn

A function that accepts up to three arguments. The reduce method calls the callbackfn function one time for each element in the iterator.

reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number) => T,initialValue: T): T;reduceU>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number) => U,initialValue: U): U;

Calls the specified callback function for all the elements in this iterator. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.

@param callbackfn

A function that accepts up to three arguments. The reduce method calls the callbackfn function one time for each element in the iterator.

@param initialValue

If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of a value from the iterator.

return(value?: undefined): IteratorResultT, undefined>;some(predicate: (value: T, index: number) => unknown): boolean;

Determines whether the specified callback function returns true for any element of this iterator.

@param predicate

A function that accepts up to two arguments. The some method calls the predicate function for each element in this iterator until the predicate returns a value true, or until the end of the iterator.

take(limit: number): IteratorObjectT, undefined, unknown>;

Creates an iterator whose values are the values from this iterator, stopping once the provided limit is reached.

@param limit

The maximum number of values to yield.

throw(e?: any): IteratorResultT, undefined>;toArray(): T[];

Creates a new array from the values yielded by this iterator.

interface UrlWithParsedQueryauth: null | stringhash: null | stringhost: null | stringhostname: null | stringhref: stringpath: null | stringpathname: null | stringport: null | stringprotocol: null | stringquery: ParsedUrlQuerysearch: null | stringslashes: null | booleaninterface UrlWithStringQueryauth: null | stringhash: null | stringhost: null | stringhostname: null | stringhref: stringpath: null | stringpathname: null | stringport: null | stringprotocol: null | stringquery: null | stringsearch: null | stringslashes: null | booleantype URLPatternInput = string | URLPatternInit

Resources

ReferenceDocsGuidesDiscordMerch StoreGitHubBlog 

Toolkit

RuntimePackage managerTest runnerBundlerPackage runner

Project

Bun 1.0Bun 1.1Bun 1.2Bun 1.3RoadmapContributingLicense

Baked with ❤️ in San Francisco

We're hiring →

Node.js url module | API Reference | Bun,AI智能索引,全网链接索引,智能导航,网页索引

    The