range-parser is a foundational utility within the Node.js ecosystem, specifically designed for parsing the HTTP `Range` header field. This header is crucial for implementing partial content responses (HTTP 206 Partial Content), enabling clients to request specific byte ranges of a resource, which is essential for video streaming, resumable downloads, and efficient data retrieval. Currently at stable version 1.2.1, it provides a straightforward API to transform a `Range` header string into a structured array of byte range objects, each with `start` and `end` properties. A key characteristic is its error handling mechanism, which returns negative integer codes (e.g., -1 for unsatisfiable ranges, -2 for malformed headers) instead of throwing exceptions, requiring developers to explicitly check the return type. It offers a `combine` option to automatically merge overlapping or adjacent ranges for simplified processing. As part of the `jshttp` organization, the package is mature and highly stable, receiving updates primarily for maintenance and minor enhancements rather than frequent new feature releases, making it a reliable choice for server-side range parsing.
npm install range-parserVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to use `range-parser` to parse HTTP `Range` headers, including basic valid range parsing, using the `combine` option, and handling common error conditions like unsatisfiable and malformed headers through its negative integer return values.
Always check `if (Array.isArray(result))` before processing the parsed ranges. If it's not an array, handle the negative integer error code appropriately (e.g., return HTTP 416 Range Not Satisfiable for -1).
Pass `{ combine: true }` as the third argument to `parseRange(size, header, { combine: true })` if you intend to merge ranges.Install `@types/range-parser` for TypeScript support (`npm install --save-dev @types/range-parser`). Be prepared to cast types or use `// @ts-ignore` for minor discrepancies if they arise, or contribute to the types definition.
Wrap calls to access `ranges` properties or methods with a check: `if (Array.isArray(ranges)) { /* ... process ranges */ } else { /* ... handle error code */ }`.Ensure the return value from `parseRange` is an array before calling array methods like `forEach`. For example: `if (Array.isArray(ranges)) { ranges.forEach(...) }`.If `parseRange` returns `-1`, your HTTP server implementation should respond with a `416 Range Not Satisfiable` status code and include a `Content-Range` header indicating the full size of the resource (e.g., `Content-Range: bytes */{fileSize}`).No dependency data recorded yet.