Small Footprint URL Parser

1.5.10 · maintenance · verified Tue Apr 21

url-parse is a URL parsing library designed for both Node.js and browser environments, emphasizing a small footprint. Originally created in 2014, it addressed the lack of a standardized WHATWG URL API across platforms. The package is currently at version 1.5.10 and receives infrequent updates, focusing on stability. It provides two distinct API interfaces: one that emulates the Node.js `url` module and another that behaves similarly to the modern browser `URL` interface. Its core differentiator is a pure string parsing approach, introduced in version 1.0.0, which ensures broad compatibility, particularly in environments without DOM access like Web Workers. It also bundles and exposes the `querystringify` module for robust query string handling. Critically, the project maintainers strongly recommend using the native `URL` interface for new development due to its superior security and accuracy, positioning `url-parse` primarily as a solution for legacy compatibility.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic URL parsing, enabling query string parsing, resolving relative URLs with a base, and direct usage of the bundled `querystringify` module.

'use strict';

const URLParse = require('url-parse');

// Basic parsing with 'new' keyword (optional)
const urlObj1 = new URLParse('https://user:pass@github.com:8080/foo/bar?baz=qux#hash');
console.log('Protocol:', urlObj1.protocol); // 'https:'
console.log('Host:', urlObj1.host);     // 'github.com:8080'
console.log('Pathname:', urlObj1.pathname); // '/foo/bar'
console.log('Query (unparsed):', urlObj1.query); // '?baz=qux'

// Parsing as a function with querystring parsing enabled
const urlObj2 = URLParse('http://localhost:3000/path?key=value&arr[]=1&arr[]=2', true);
console.log('Protocol:', urlObj2.protocol); // 'http:'
console.log('Query (parsed):', urlObj2.query); // { key: 'value', arr: [ '1', '2' ] }

// Using a base URL for relative paths
const baseUrl = 'http://example.com/a/b/';
const relativeUrlObj = new URLParse('../c', baseUrl);
console.log('Resolved Path:', relativeUrlObj.pathname); // '/a/c'
console.log('Resolved URL:', relativeUrlObj.href); // 'http://example.com/a/c'

// Accessing querystringify directly
const querystringify = require('url-parse/lib/querystringify');
const qString = querystringify.stringify({ name: 'Alice', age: 30 });
console.log('Stringified Query:', qString); // 'name=Alice&age=30'

view raw JSON →