CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-url-parse

Small footprint URL parser that works seamlessly across Node.js and browser environments

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

URL Parse

URL Parse is a lightweight, high-performance URL parsing library that works seamlessly across Node.js and browser environments. It provides a pure string-based parsing algorithm with a minimal footprint, offering both Node.js-style url.parse() and modern URL constructor interfaces for maximum compatibility.

Package Information

  • Package Name: url-parse
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install url-parse

Core Imports

var Url = require('url-parse');

ES6 modules (if supported by bundler):

import Url from 'url-parse';

Basic Usage

var Url = require('url-parse');

// Parse a complete URL
var url = new Url('https://user:pass@github.com:443/foo/bar?hello=world#readme');

console.log(url.protocol);   // 'https:'
console.log(url.hostname);   // 'github.com'
console.log(url.pathname);   // '/foo/bar'
console.log(url.query);      // 'hello=world'
console.log(url.hash);       // '#readme'

// Parse with query string parsing enabled
var urlWithQuery = new Url('https://example.com?name=john&age=30', null, true);
console.log(urlWithQuery.query); // { name: 'john', age: '30' }

// Parse relative URL with base URL
var relative = new Url('/api/users', 'https://example.com');
console.log(relative.href); // 'https://example.com/api/users'

// Node.js-style parsing
var parsed = Url('https://example.com/path?query=value', true);

Architecture

URL Parse is built around several key components that enable efficient and accurate URL parsing:

  • Pure String Parsing: Uses a custom string-based parsing algorithm instead of RegExp or DOM-based approaches for better performance and cross-environment compatibility
  • Rules-Based Processing: Employs a parsing rules array that defines the order and method for extracting URL components (hash, query, pathname, auth, host, port, hostname)
  • Protocol Handling: Special handling for different protocol schemes (file:, ftp:, http:, https:, ws:, wss:) with appropriate path and slash processing
  • Location Context: Intelligent base URL resolution using browser location or custom location objects for relative URL parsing
  • Property Propagation: The set() method ensures changes to one property automatically update related properties (e.g., changing hostname updates host)
  • Query Integration: Seamless integration with querystringify for flexible query string parsing and stringification

The parsing process follows a systematic approach: protocol extraction, rules-based component parsing, authentication handling, hostname/port normalization, pathname resolution, and final href/origin computation.

Capabilities

URL Constructor

Creates a new URL instance by parsing the provided URL string.

/**
 * Parse URL and create URL instance
 * @param address - URL string to parse (absolute or relative)
 * @param location - Base URL for relative parsing or location defaults
 * @param parser - Query string parser (boolean or function)
 * @returns Url instance
 */
function Url(address, location, parser);

Parameters:

  • address (String): URL string to parse (absolute or relative)
  • location (Object|String, optional): Base URL for relative parsing. In browsers, defaults to window.location. Pass empty object {} for environment-independent parsing.
  • parser (Boolean|Function, optional):
    • false (default): Query string remains as string
    • true: Parse query using built-in querystringify
    • Function: Custom query string parser function

Usage Examples:

// Basic parsing
var url = new Url('https://example.com/path');

// With query parsing
var url = new Url('https://example.com/path?a=1&b=2', null, true);

// Relative URL with base
var url = new Url('/api', 'https://example.com');

// Custom query parser
var url = new Url('https://example.com?data', null, customParser);

// Node.js style (without 'new')
var url = Url('https://example.com/path', true);

URL Properties

All parsed URL components are available as instance properties:

interface UrlInstance {
  /** Protocol scheme including colon (e.g., 'http:') */
  protocol: string;
  /** Whether protocol is followed by '//' */
  slashes: boolean;
  /** Authentication info as 'username:password' */
  auth: string;
  /** Username portion of authentication */
  username: string;
  /** Password portion of authentication */
  password: string;
  /** Hostname with port number */
  host: string;
  /** Hostname without port number */
  hostname: string;
  /** Port number as string */
  port: string;
  /** URL path portion */
  pathname: string;
  /** Query string (string or parsed object based on parser) */
  query: string | object;
  /** Fragment portion including '#' */
  hash: string;
  /** Complete URL string */
  href: string;
  /** Origin (protocol + hostname + port) */
  origin: string;
}

Set Method

Modify URL properties with automatic propagation to related properties.

/**
 * Change URL properties with automatic updates to related properties
 * @param part - Property name to set
 * @param value - New value for the property
 * @param fn - Additional options (parser for query, slash handling for protocol)
 * @returns Url instance (for chaining)
 */
set(part, value, fn);

Supported Properties:

  • 'protocol': Updates protocol, may affect slashes
  • 'hostname': Updates hostname, propagates to host
  • 'host': Updates both hostname and port
  • 'port': Updates port, propagates to host, handles default ports
  • 'pathname': Updates path portion
  • 'query': Updates query string, can use custom parser
  • 'hash': Updates fragment portion
  • 'username': Updates username, propagates to auth
  • 'password': Updates password, propagates to auth
  • 'auth': Updates authentication, splits into username/password

Usage Examples:

var url = new Url('http://example.com/path');

// Change hostname
url.set('hostname', 'newhost.com');
console.log(url.href); // 'http://newhost.com/path'

// Change port (automatically updates host)
url.set('port', '8080');
console.log(url.host); // 'newhost.com:8080'

// Change query with parsing
url.set('query', 'name=value&type=test', true);
console.log(url.query); // { name: 'value', type: 'test' }

// Method chaining
url.set('protocol', 'https:').set('pathname', '/api');

ToString Method

Generate complete URL string from the instance properties.

/**
 * Generate complete URL string
 * @param stringify - Custom query string stringify function
 * @returns Complete URL as string
 */
toString(stringify);

Usage Examples:

var url = new Url('https://example.com/path?name=value');

// Default stringification
var urlString = url.toString();
console.log(urlString); // 'https://example.com/path?name=value'

// Custom query stringifier
var customString = url.toString(customStringifyFunction);

// Also available as href property
console.log(url.href === url.toString()); // true

Static Utility Methods

Additional utility methods available on the Url constructor:

/**
 * Extract protocol information from URL
 * @param address - URL string to extract from  
 * @param location - Optional location defaults
 * @returns Object with protocol, slashes, rest, and slashesCount properties
 */
Url.extractProtocol(address, location);

/**
 * Generate location object for URL parsing
 * @param loc - Default location object
 * @returns Location object with URL properties
 */
Url.location(loc);

/**
 * Remove control characters and whitespace from string beginning
 * @param str - String to trim
 * @returns Trimmed string
 */
Url.trimLeft(str);

/**
 * Reference to querystringify module for query operations
 */
Url.qs;

Usage Examples:

// Extract protocol info
var protocolInfo = Url.extractProtocol('https://example.com/path');
console.log(protocolInfo.protocol);     // 'https:'
console.log(protocolInfo.slashes);      // true
console.log(protocolInfo.rest);         // 'example.com/path'
console.log(protocolInfo.slashesCount); // 2

// Trim whitespace
var clean = Url.trimLeft('  \t\n  hello world');
console.log(clean); // 'hello world'

// Access query string utilities
var queryString = Url.qs.stringify({ name: 'value', type: 'test' });
var queryObject = Url.qs.parse('name=value&type=test');

Error Handling

URL Parse handles malformed URLs gracefully by:

  • Defaulting missing components to empty strings
  • Preserving invalid hostnames and ports for inspection
  • Handling special protocols (file:, ftp:, http:, https:, ws:, wss:) appropriately
  • Supporting both absolute and relative URL parsing

For robust error handling, validate critical properties after parsing:

var url = new Url(userInput);

// Validate hostname exists
if (!url.hostname) {
  throw new Error('Invalid URL: missing hostname');
}

// Validate protocol is expected
if (!['http:', 'https:'].includes(url.protocol)) {
  throw new Error('Invalid protocol: ' + url.protocol);
}

Browser vs Node.js Differences

  • Browser: Defaults to window.location as base URL for relative URLs
  • Node.js: No default base URL, relative URLs parse with empty location
  • Environment-independent parsing: Pass empty object {} as second parameter
// Browser-dependent (uses window.location in browser)
var url = new Url('/api/users');

// Environment-independent 
var url = new Url('/api/users', {});

docs

index.md

tile.json