HTTP Range Header Parser (JavaScript)
Parse a single-range HTTP Range header, resolve open ends against a resource size and return a satisfiable byte range.
Code
export function parseRange(header, size) {
if (!header || typeof header !== 'string') return null;
const match = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
if (!match) return { unsatisfiable: true };
const [, startRaw, endRaw] = match;
if (startRaw === '' && endRaw === '') return { unsatisfiable: true };
let start;
let end;
if (startRaw === '') {
const suffix = Number(endRaw);
if (suffix === 0) return { unsatisfiable: true };
start = Math.max(size - suffix, 0);
end = size - 1;
} else {
start = Number(startRaw);
end = endRaw === '' ? size - 1 : Number(endRaw);
}
if (start > end || start >= size) return { unsatisfiable: true };
return { start, end: Math.min(end, size - 1), length: Math.min(end, size - 1) - start + 1 };
}Report a problem with this exampleOpens a pre-filled issue on GitHub.