Skip to content

Commit

Permalink
Extract and modernize the webserver's range file serving code
Browse files Browse the repository at this point in the history
The `handler` method contained this code in an inline function, which
made the `handler` method big and harder to read. Moreover, this code
relied on variables from the outer scope, which made it harder to reason
about because the inputs and outputs weren't easily visible.

This commit fixes the problems by extracting the range file serving code
into a dedicated private method, and modernizing it to use e.g. `const`/
`let` instead of `var` and using template strings.
  • Loading branch information
timvandermeij committed Feb 11, 2024
1 parent 56d9930 commit 336fcff
Showing 1 changed file with 28 additions and 28 deletions.
56 changes: 28 additions & 28 deletions test/webserver.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -182,8 +182,10 @@ class WebServer {
if (verbose) {
console.log(url + ": range " + start + " - " + end);
}
serveRequestedFileRange(
self.#serveFileRange(
res,
filePath,
fileSize,
start,
isNaN(end) ? fileSize : end + 1
);
Expand Down Expand Up @@ -285,33 +287,6 @@ class WebServer {
res.end("</body></html>");
});
}

function serveRequestedFileRange(reqFilePath, start, end) {
var stream = fs.createReadStream(reqFilePath, {
flags: "rs",
start,
end: end - 1,
});

stream.on("error", function (error) {
res.writeHead(500);
res.end();
});

var ext = path.extname(reqFilePath).toLowerCase();
var contentType = mimeTypes[ext] || defaultMimeType;

res.setHeader("Accept-Ranges", "bytes");
res.setHeader("Content-Type", contentType);
res.setHeader("Content-Length", end - start);
res.setHeader(
"Content-Range",
"bytes " + start + "-" + (end - 1) + "/" + fileSize
);
res.writeHead(206);

stream.pipe(res);
}
}

#serveFile(response, filePath, fileSize) {
Expand All @@ -337,6 +312,31 @@ class WebServer {
response.writeHead(200);
stream.pipe(response);
}

#serveFileRange(response, filePath, fileSize, start, end) {
const stream = fs.createReadStream(filePath, {
flags: "rs",
start,
end: end - 1,
});
stream.on("error", error => {
response.writeHead(500);
response.end();
});

const extension = path.extname(filePath).toLowerCase();
const contentType = mimeTypes[extension] || defaultMimeType;

response.setHeader("Accept-Ranges", "bytes");
response.setHeader("Content-Type", contentType);
response.setHeader("Content-Length", end - start);
response.setHeader(
"Content-Range",
`bytes ${start}-${end - 1}/${fileSize}`
);
response.writeHead(206);
stream.pipe(response);
}
}

// This supports the "Cross-origin" test in test/unit/api_spec.js
Expand Down

0 comments on commit 336fcff

Please sign in to comment.