Determine which byte intervals a client requested before constructing a 206 response.
Serving partial content
Express.js · Pipe
Parses the HTTP Range header for a resource of a specified size. It returns requested ranges or a negative error code, with an option to merge overlapping and adjacent ranges.
Call req.range with the resource size to parse the HTTP Range header. The result is an array-like collection whose type identifies the range unit; it can instead be a negative status code for malformed or unsatisfiable input, and the combine option merges overlapping or adjacent ranges.
req.range(size, options)| Name | Type | Description |
|---|---|---|
size | Number | Maximum size of the resource being parsed. |
options | Object | undefined | Optional parsing options for the Range header. |
options.combine | Boolean | Whether to combine overlapping and adjacent ranges; defaults to false. |
An array of ranges, or -2 for a malformed header and -1 for an unsatisfiable range.
const express = require('express');
const app = express();
app.get('/file', (req, res) => {
const range = req.range(1000, { combine: true });
if (range === -2) return res.status(400).send('Malformed Range header');
if (range === -1) return res.status(416).send('Range not satisfiable');
res.json({ type: range.type, ranges: [...range] });
});
app.listen(3000);Parses the request's Range header for a resource up to 1000 units, combining overlapping or adjacent ranges.
Serving partial content
Validating download requests
Normalizing multiple intervals
req.range(size) parses the request's Range header against the resource's maximum size. It returns an array of ranges or a negative number when parsing fails.
Follow-up: What do the negative results mean? -2 indicates a malformed header, while -1 indicates an unsatisfiable range.
The size argument is the maximum size of the resource being ranged. The parser uses it to interpret open-ended and bounded ranges safely.
Follow-up: Why should the size match the actual resource? An incorrect maximum can produce boundaries that do not correspond to the resource being served.
Pass an options object with combine set to true when overlapping and adjacent ranges should be merged. The default is false, so ranges remain represented separately unless combining is requested.
Follow-up: When might combining help? It can reduce redundant range segments before application code constructs a partial response.
req.headersres.status()res.send()res.set()