Range header field parser.
npm install range-parserimport { parse, format, combineRanges } from "range-parser";Parse the given header string where size is the size of the selected representation that is to be partitioned into subranges. Always returns an object with code, type, and ranges properties.
code: 0means all ranges were parsed successfully.code: 1means the header was malformed.code: 2means one or more ranges were unsatisfiable.code: 3means both malformed and unsatisfiable ranges were encountered (1 | 2).
Type is always lower case and is not validated against RFC token syntax, make sure to validate before using (e.g. type === "bytes").
Ranges contain all valid and satisfiable ranges with inclusive start and end positions.
parse(200, "bytes=0-99,x-,500-");
// => {
// code: 3,
// type: "bytes",
// ranges: [{ start: 0, end: 99 }]
// }Note: size must be a safe integer or a TypeError is thrown. The maximum supported file size is Number.MAX_SAFE_INTEGER (9,007,199,254,740,991 bytes), about 9 PB.
// parse header from request
var header = req.headers.range;
var subranges = parse(size, typeof header === "string" ? header : "");
// Process headers whose ranges are all valid and satisfiable.
if (subranges.type === "bytes" && subranges.ranges.length) {
subranges.ranges.forEach((r) => {
// Do something with r.start and r.end
});
}Format an object containing a range unit type and an array of ranges with inclusive start and end positions as a Range header.
format({
type: "bytes",
ranges: [
{ start: 0, end: 99 },
{ start: 200, end: 299 },
],
});
// => "bytes=0-99,200-299"
format({ type: "items", ranges: [{ start: 0, end: 5 }] });
// => "items=0-5"
format(parse(1000, "bytes=900-,-10"));
// => "bytes=900-999,990-999"Throws a TypeError if the object contains an invalid type or range.
Overlapping and adjacent ranges will be combined and returned.
Returned ranges include the index used to preserve their original order.
const subranges = parse(100, "bytes=50-55,0-10,5-10,56-60");
if (subranges.ranges.length) {
combineRanges(subranges.ranges);
// => [
// { start: 50, end: 60, index: 0 },
// { start: 0, end: 10, index: 1 }
// ]
}