Skip to content

Commit

Permalink
Fixing range handling within stream() & adding a test
Browse files Browse the repository at this point in the history
  • Loading branch information
avoidwork committed Dec 27, 2020
1 parent 40b596d commit 950e4fa
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
9 changes: 6 additions & 3 deletions lib/utility.js
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,10 @@ function stream (req, res, file = {charset: "", etag: "", path: "", stats: {mtim

// Setting the partial content headers
if ("range" in req.headers) {
for (const [idx, i] of req.headers.range.replace(/^.*=/, "").split(",")[0].split("-")) {
options[idx === 0 ? "start" : "end"] = i ? parseInt(i, 10) : void 0;
const range = req.headers.range.replace(/^.*=/, "").split(",")[0].split("-");

for (const [idx, i] of range.entries()) {
options[idx === 0 ? "start" : "end"] = i !== void 0 ? parseInt(i, 10) : void 0;
}

// Byte offsets
Expand All @@ -155,9 +157,10 @@ function stream (req, res, file = {charset: "", etag: "", path: "", stats: {mtim
}

status = 206;
res.removeHeader("content-length");
res.removeHeader("etag"); // Removing etag since this rep is incomplete
res.header("content-range", `bytes ${options.start}-${options.end}/${file.stats.size}`);
res.header("content-length", options.end - options.start + 1);
res.removeHeader("etag"); // Removing etag since this rep is incomplete
}

res.send(fs.createReadStream(file.path, options), status);
Expand Down
8 changes: 8 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,14 @@ describe("Valid Requests", function () {
.end();
});

it("GET /test/test.js (206 / 'Partial response - bytes=0-5')", function () {
return tinyhttptest({url: "http://localhost:8001/test/test.js", headers: {range: "bytes=0-5"}})
.expectStatus(206)
.expectHeader("content-type", "application/javascript; charset=utf-8")
.expectHeader("content-length", 6)
.end();
});

it("HEAD /test/test.js (200 / 'Success')", function () {
return tinyhttptest({url: "http://localhost:8001/test/test.js", method: "HEAD"})
.expectStatus(200)
Expand Down

0 comments on commit 950e4fa

Please sign in to comment.