Comprehensive Guide to the URL Module in Node.js

The node:url module provides tools for parsing, constructing, and manipulating URLs. Node.js supports two URL APIs: WHATWG URL API — modern, browser‑compatible, standards‑based. Legacy Node.js URL API — older, Node‑specific, now discouraged. The WHATWG API is the recommended approach for all modern applications. It provides a clean, consistent interface for working with URL components, query parameters, and structured URL patterns.

WHATWG URLLegacy url.parseURLSearchParamsURLPattern

~3 دقیقه مطالعه · آخرین به‌روزرسانی ۹ دی ۱۴۰۴

1. Introduction


The node:url module provides utilities for parsing and formatting URLs. Node.js supports both a legacy API and the modern WHATWG URL Standard used by browsers.


2. URL Strings and URL Objects


A URL string contains structured components such as protocol, hostname, port, path, query, and hash. Parsing a URL returns an object exposing these components.


3. WHATWG vs Legacy API


Node.js provides two parsing styles:

  • WHATWG URLnew URL() (recommended)
  • Legacy APIurl.parse() (deprecated)

Example (WHATWG):

const myURL = new URL('https://user:[email protected]:8080/p/a/t/h?query=string#hash');

Example (Legacy):

const url = require('node:url');
const myURL = url.parse('https://user:[email protected]:8080/p/a/t/h?query=string#hash');

4. Constructing URLs


You can build URLs using setters or template literals:

const myURL = new URL('https://example.org');
myURL.pathname = '/a/b/c';
myURL.search = '?d=e';
myURL.hash = '#fgh';

5. The WHATWG URL API


The WHATWG URL class is browser‑compatible and available globally.

5.1 new URL(input, base)


Parses absolute or relative URLs. Relative URLs require a base.

5.2 Unicode & Punycode


new URL('https://測試'); // → https://xn--g6w251d/

6. URL Component Properties


6.1 url.hash

Gets/sets the fragment (#...)

6.2 url.host

Hostname + port

6.3 url.hostname

Hostname only

6.4 url.href

Full serialized URL

6.5 url.origin

Protocol + host

6.6 url.password / url.username

Authentication fields

6.7 url.pathname

Path portion

6.8 url.port

Port number (0–65535)

6.9 url.protocol

Protocol (http:, https:, ftp:, etc.)

Special Schemes

Only certain protocols are “special”: http, https, ftp, file, ws, wss.


7. url.search and url.searchParams


url.search is the raw query string. url.searchParams is a structured interface for manipulating query parameters.

Examples:

myURL.searchParams.get('abc');
myURL.searchParams.append('key', 'value');
myURL.searchParams.delete('abc');
myURL.searchParams.set('a', 'b');

8. URLSearchParams API


Can be used standalone or via url.searchParams.

Constructors:

  • Empty → new URLSearchParams()
  • String → new URLSearchParams('a=b&c=d')
  • Object → new URLSearchParams({ a: 'b' })
  • Iterable → new URLSearchParams([['a','b']])

Key Methods:

  • append(name, value)
  • delete(name[, value])
  • get(name)
  • getAll(name)
  • has(name[, value])
  • set(name, value)
  • sort()

9. Blob Object URLs


Node.js supports creating in‑memory Blob URLs:

const id = URL.createObjectURL(blob);
const restored = resolveObjectURL(id);
URL.revokeObjectURL(id);

10. URL.canParse()


Checks if a URL is valid without throwing:

URL.canParse('/foo', 'https://example.org/'); // true

11. URL.parse()


A safe parser that returns null instead of throwing.


12. URLPattern API


Experimental API for matching URLs against patterns.

Example:

const pattern = new URLPattern('https://site.com/docs/*.html');
pattern.test('https://site.com/docs/api.html'); // true

Conclusion


The node:url module provides a powerful, standards‑compliant system for parsing, constructing, and manipulating URLs. The WHATWG URL API is the modern, browser‑compatible approach and should be used for all new development. With support for URLSearchParams, Blob URLs, URLPattern, and robust parsing rules, Node.js offers a complete toolkit for working with URLs in any environment.


نوشته و پژوهش‌شده توسط دکتر شاهین صیامی

مقالات مرتبط

Comprehensive Guide to the Node.js VM Module (node:vm)

The node:vm module allows you to compile and execute JavaScript code inside isolated V8 contexts — essentially creating lightweight sandboxes within your Node.js application. These contexts have their own global scope and can run code independently from the main environment. However, vm is NOT a security sandbox. It is powerful for dynamic code execution, template engines, REPLs, plugin systems, and controlled module execution, but it must never be used to run untrusted code.

ادامه

Comprehensive Guide to the V8 Module in Node.js (node:v8)

The node:v8 module exposes low-level APIs that interact directly with the V8 JavaScript engine embedded in Node.js. . These APIs provide access to heap statistics, heap snapshots, coverage tools, serialization mechanisms, V8 flags, object queries, and promise lifecycle hooks. The module is essential for performance analysis, memory debugging, tooling, and advanced Node.js internals work.

ادامه

Comprehensive Guide to Node.js Worker Threads (node:worker_threads)

The node:worker_threads module enables true multithreading in Node.js by running JavaScript in separate threads. While Node.js is traditionally single‑threaded, worker threads allow CPU‑intensive tasks to run in parallel without blocking the event loop. They support shared memory, zero‑copy transfers, worker pools, resource limits, and advanced synchronization APIs. Worker threads are ideal for heavy computation, data processing, and parallel workloads—while async I/O remains best handled by the main thread.

ادامه

Comprehensive Guide to the Node.js util Module (node:util)

The node:util module provides a powerful collection of helper functions used throughout Node.js core and extremely useful for application developers. These utilities support debugging, inspection, formatting, type checking, callback/Promise conversions, argument parsing, text encoding, MIME handling, and more. It is one of the most versatile and essential toolkits in the Node.js ecosystem.

ادامه

راهنمای جامع UDP / Datagram Sockets در Node.js

ماژول node:dgram پیاده‌سازی کامل سوکت‌های UDP را در Node.js فراهم می‌کند. UDP یک پروتکل سبک، بدون اتصال (connectionless) و مناسب برای برنامه‌های بلادرنگ مانند VoIP، بازی‌ها، IoT، سیستم‌های پخش (broadcast) و چندپخشی (multicast) است. این ماژول امکان ساخت سوکت، ارسال و دریافت دیتاگرام، مدیریت TTL، عضویت در گروه‌های multicast، کنترل بافرها، و مدیریت رفتار سطح پایین شبکه را فراهم می‌کند.

ادامه

Comprehensive Guide to Trace Events and TTY in Node.js

Node.js provides two powerful low‑level modules for diagnostics and terminal interaction: node:trace_events — a high‑resolution tracing system that captures internal activity from V8, Node.js core, and userland code. It is essential for profiling, performance analysis, and deep debugging. node:tty — a module that exposes TTY (terminal) interfaces, enabling advanced CLI tools, raw input handling, cursor control, color detection, and terminal resizing. This guide explains both modules in a clean, structured, and practical way.

ادامه