File download and byte ranges
Prerequisites: previous curriculum lessons on Node streams, HTTP, buffers and asynchronous errors. Local lab baseline: Node.js 22.16.0, Linux, ESM. Use a disposable directory. Static examples are not ByteMind interactive execution. Each example is independent; save the named files together and run node main.mjs. The author harness imposes a five-second process deadline.
How it works
Offsets refer to bytes, not JavaScript string indexes. For a representation of 10 bytes, bytes=2-5 selects four bytes. Buffer.subarray uses an exclusive end, so add one to the inclusive last position. A valid but unsatisfiable range can receive 416 with Content-Range: bytes */10. A server can ignore a Range request and return the full 200 response; multi-range and suffix ranges require additional logic. Our intentionally restricted handler supports only explicit start-end single ranges and ignores other syntax. It serves a fixed uncompressed representation; a production server also handles validators, If-Range, HEAD, conditional requests, file mutation and content negotiation.
Calculate inclusive byte positions
const data=Buffer.from('0123456789');const start=2,end=5;const result=data.subarray(start,end+1);console.log(result.toString(),result.length);console.log(`bytes ${start}-${end}/${data.length}`);Expected output:
2345 4bytes 2-5/10Four bytes include positions 2, 3, 4 and 5.
Verify real HTTP 206 and 416 responses on loopback
import http from 'node:http';import {once} from 'node:events';const body=Buffer.from('0123456789');const server=http.createServer((req,res)=>{ const match=/^bytes=(\d{1,6})-(\d{1,6})$/.exec(req.headers.range??''); if(!match||Number(match[2])<Number(match[1])){res.writeHead(200,{'Content-Length':body.length});return res.end(body);} const start=Number(match[1]),end=Math.min(Number(match[2]),body.length-1); if(start>=body.length){res.writeHead(416,{'Content-Range':`bytes */${body.length}`});return res.end();} const part=body.subarray(start,end+1); res.writeHead(206,{'Content-Range':`bytes ${start}-${end}/${body.length}`,'Content-Length':part.length});res.end(part);});server.listen(0,'127.0.0.1');await once(server,'listening');try {for(const range of ['bytes=2-5','bytes=8-20','bytes=10-12']){ const r=await fetch('http://127.0.0.1:'+server.address().port,{headers:{Range:range},signal:AbortSignal.timeout(1500)}); console.log(r.status,r.headers.get('content-range'),(await r.text())||'(empty)');}}finally{server.closeAllConnections();await new Promise(r=>server.close(r));}Expected output:
206 bytes 2-5/10 2345206 bytes 8-9/10 89416 bytes */10 (empty)These actual requests check accepted, clamped and unsatisfiable explicit ranges. Unsupported range syntax is deliberately ignored.
Common mistakes
Never use raw URL segments as filesystem paths or calculate Content-Length from character count. Apply authorization before serving bytes, including partial responses. Do not advertise a toy parser as a full HTTP range implementation.
Practice
For a 12-byte representation, calculate the result of bytes=10-20 and bytes=12-20. Explain why the first is clamped and the second unsatisfiable.
Further reading
Official documentation: rfc9110. Internal reference candidate: node-file-download-and-byte-ranges-lookup (route not verified).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
File download and byte ranges — knowledge check
Apply the lesson to a fresh scenario and explain the resource or protocol boundary.
How many bytes does bytes=3-5 select?
What is the correct Content-Range for an unsatisfiable request on a 10-byte body?
Why should a range handler authorize before serving a partial body?