Range header field parser.
npm install range-parserimport { parse, 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).
ranges contains all valid and satisfiable ranges. Each range has 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
});
}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 }
// ]
}