forked from Tomas/webdl
Added HTTP range support
This commit is contained in:
45
src/index.ts
45
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();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user