1.0.0 • Published 6 months ago

biscuit-url v1.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
6 months ago

URL Parser for HTTP Requests

A lightweight and efficient URL parser for HTTP requests, designed to enhance performance and maintain consistency in request handling.

Features

  • Fast and lightweight: Uses Node.js built-in URL module.

  • Automatic caching: Stores parsed results in req._parsedUrl to avoid redundant computations.

  • Graceful error handling: Returns a fallback object if the URL parsing fails.

  • Immutable results: Uses Object.freeze() to ensure parsed objects remain unchanged.

Installation

npm install biscuit-url

Usage

'use strict';

const http = require('http');
const parseUrl = require('./urlParser'); // Adjust path as needed

const server = http.createServer((req, res) => {
  const parsedUrl = parseUrl(req);

  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(parsedUrl, null, 2));
});

server.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

API

parseUrl(req) => ParsedUrlObject

Parameters

req (Object) – The HTTP request object.

Returns

A frozen object containing:

  • query (URLSearchParams) – Parsed query parameters.

  • search (string|null) – Query string including ?, or null if absent.

  • href (string) – Full URL string.

  • path (string) – Path with query string (e.g., /test?name=example).

  • pathname (string) – Path without query string (e.g., /test).

  • _raw (string) – Original URL before parsing.

Example Output

Request

curl "http://localhost:3000/test?name=example"

Response

{
  "query": {
    "name": "example"
  },
  "search": "?name=example",
  "href": "http://localhost/test?name=example",
  "path": "/test?name=example",
  "pathname": "/test",
  "_raw": "/test?name=example"
}

Error Handling

If the URL is invalid, a default object is returned:

{
  "query": null,
  "search": null,
  "href": "/invalid_url",
  "path": "/invalid_url",
  "pathname": "/invalid_url",
  "_raw": "/invalid_url"
}

Notes

A base URL (http://localhost) is added to avoid errors when parsing relative URLs.

The query property is an instance of URLSearchParams and provides methods like .get() and .has().

License

MIT License.

1.0.0

6 months ago