Bun

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) => URL
  • const URLSearchParams: new (init?: string | string[][] | URLSearchParams | Record<string, string>) => URLSearchParams
  • function 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,
    ): 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:///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)
    
    @param url

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

    @returns

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

  • url: string | URL,
    ): 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.

    @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.

  • function format(
    urlObject: URL,
    ): 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&#x26;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 // 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: string | 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&#x26;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 // 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 pathToFileURL(
    path: string,
    ): 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:///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)
    
    @param path

    The path to convert to a File URL.

    @returns

    The file URL object.

  • function resolve(
    from: string,
    to: string
    ): string;

    The url.resolve() method resolves a target URL relative to a base URL in a manner similar to that of a web browser resolving an anchor tag.

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

    To achieve the same result using the 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'
    
    @param from

    The base URL to use if to is a relative URL.

    @param to

    The target URL to resolve.

  • url: URL

    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

Type definitions

  • interface FileUrlToPathOptions

    • windows?: boolean

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

  • interface PathToFileUrlOptions

    • windows?: boolean

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

  • interface Url

  • interface URL

  • interface URLFormatOptions

    • auth?: 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 UrlObject

  • interface URLPatternComponentResult

    • groups: Record<string, undefined | string>
    • input: string
  • interface URLPatternInit

  • interface URLPatternOptions

  • interface URLSearchParams

  • interface URLSearchParamsIterator<T>

    • readonly [Symbol.toStringTag]: string
    • count: number
      ): IteratorObject<T, 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.

    • 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.

    • filter<S>(
      predicate: (value: T, index: number) => value is S
      ): IteratorObject<S, 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.

      predicate: (value: T, index: number) => unknown
      ): IteratorObject<T, 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.

    • find<S>(
      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.

      predicate: (value: T, index: number) => unknown
      ): undefined | T;
    • callback: (value: T, index: number) => Iterator<U, unknown, undefined> | Iterable<U, unknown, undefined>
      ): IteratorObject<U, 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.

    • 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.

    • map<U>(
      callbackfn: (value: T, index: number) => U
      ): IteratorObject<U, 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.

    • ...__namedParameters: [] | [unknown]
      ): IteratorResult<T, undefined>;
    • 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.

      callbackfn: (previousValue: T, currentValue: T, currentIndex: number) => T,
      initialValue: T
      ): T;
      reduce<U>(
      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.

    • value?: undefined
      ): IteratorResult<T, undefined>;
    • 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.

    • limit: number
      ): IteratorObject<T, 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.

    • e?: any
      ): IteratorResult<T, undefined>;
    • toArray(): T[];

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

  • interface UrlWithParsedQuery

  • interface UrlWithStringQuery