From 336fcffd283f39b4a2663edcbe101cbb4843a8c5 Mon Sep 17 00:00:00 2001 From: Tim van der Meij Date: Sun, 11 Feb 2024 13:49:42 +0100 Subject: [PATCH] Extract and modernize the webserver's range file serving code 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. --- test/webserver.mjs | 56 +++++++++++++++++++++++----------------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/test/webserver.mjs b/test/webserver.mjs index 0149eadc5833d..57c913d66a977 100644 --- a/test/webserver.mjs +++ b/test/webserver.mjs @@ -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 ); @@ -285,33 +287,6 @@ class WebServer { res.end(""); }); } - - 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) { @@ -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