WHATWG URL Utilities

2.4.1 · active · verified Sun Apr 19

bare-url is a JavaScript library providing a WHATWG URL Standard-compliant implementation for parsing, formatting, and manipulating URLs. As of version 2.4.1, it offers a robust set of utilities, including conversions between file paths and URL objects. It ships with comprehensive TypeScript type definitions, enabling strong type-checking in modern development environments. The package is actively maintained, indicated by its numerous versions and frequent recent updates, ensuring adherence to the evolving WHATWG standard. While Node.js provides a global `URL` class that aligns with the WHATWG specification, `bare-url` can serve as a consistent, lightweight alternative or a reliable polyfill in environments where the native `URL` might be absent, outdated, or exhibit inconsistent behavior. Its focus is on providing a dependable, spec-compliant URL API.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates converting between file paths and URLs, and parsing a complex URL string into its components using the `bare-url` utilities.

import { fileURLToPath, pathToFileURL, URL } from 'bare-url';

// Convert a file URL to a path string
const filePath = fileURLToPath('file:///home/user/document.txt');
console.log(`File URL to path: ${filePath}`);
// Expected: /home/user/document.txt

// Convert a path string to a file URL
const fileUrl = pathToFileURL('/usr/local/data/report.pdf');
console.log(`Path to file URL: ${fileUrl.toString()}`);
// Expected: file:///usr/local/data/report.pdf

// Create and parse a new URL object
const myUrl = new URL('https://example.com:8080/path/to/resource?query=param#hash');
console.log(`
Parsed URL details:`
  + `\n  Origin: ${myUrl.origin}`
  + `\n  Hostname: ${myUrl.hostname}`
  + `\n  Port: ${myUrl.port}`
  + `\n  Pathname: ${myUrl.pathname}`
  + `\n  Search Params: ${myUrl.searchParams.get('query')}`);
// Expected: example.com, 8080, /path/to/resource, param

view raw JSON →