From fc664848f7c65b19916a8ee9035112bb5f507ef3 Mon Sep 17 00:00:00 2001 From: Tomas Date: Sat, 10 Jan 2026 08:23:25 +0100 Subject: [PATCH] Added HTTP range support --- src/index.ts | 45 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/src/index.ts b/src/index.ts index 10bcc9d..65de07f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -80,9 +80,48 @@ app.get("/api/data/:id", async (req, res)=>{ const head = Buffer.concat(head_chunks); detectBufferMime(head).then((mime)=>{ res.contentType(mime); - res.write(head); - stream.pipe(res); - stream.resume(); + res.header("Accept-Ranges", "bytes"); + const range = req.range(dl.received); + if (range) + { + if (typeof(range) == "number") + return res.status(400).send({error:"Invalid range"}); + + const r = range[0]!; + r.end += 1; + + res.status(206); + res.header("Content-Range", `bytes ${r.start}-${r.end-1}/${dl.received}`); + res.header("Content-Length", String(r.end - r.start)); + if (r.start < head.length) + res.write(head.slice(r.start, r.end)); + + if ((r.end-r.start) - head.length <= 0) + return res.end(); + + let start = r.start-head.length; + let end = r.end-head.length; + stream.on("data", (chunk)=>{ + if (start < chunk.length) + res.write(chunk.slice(Math.max(0, start), end)); + start -= chunk.length; + end -= chunk.length; + if (end <= 0) + { + res.end(); + stream.pause(); + stream.destroy(); + } + }); + stream.resume(); + } + else + { + res.header("Content-Length", String(dl.received)); + res.write(head); + stream.pipe(res); + stream.resume(); + } }); } }