From 453859194f29719b190d12f7c5c0190c820afdef Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Thu, 21 Mar 2024 09:45:41 +0000 Subject: [PATCH] fix: `ContentLength` incorrectly set for empty files A regression was introduced in the latest version wherein files with zero bytes would have their `ContentLength` erroneously set to `1`. This resulted in requests failing with an `ERR_CONTENT_LENGTH_MISMATCH`. --- src/utils/compatibleAPI.js | 4 +++- test/middleware.test.js | 17 ++++++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/utils/compatibleAPI.js b/src/utils/compatibleAPI.js index b168f040d..4d2f81fdc 100644 --- a/src/utils/compatibleAPI.js +++ b/src/utils/compatibleAPI.js @@ -267,7 +267,9 @@ async function send(req, res, filename, start, end, goNext, options) { start, end, }); - byteLength = end - start + 1; + + // Handle files with zero bytes + byteLength = end === 0 ? 0 : end - start + 1; } else { bufferOrStream = /** @type {import("fs").readFileSync} */ ( options.outputFileSystem.readFileSync diff --git a/test/middleware.test.js b/test/middleware.test.js index ead7886fc..663bb3eba 100644 --- a/test/middleware.test.js +++ b/test/middleware.test.js @@ -124,6 +124,11 @@ describe.each([ "unknown", ); + instance.context.outputFileSystem.writeFileSync( + path.resolve(outputPath, "empty-file.txt"), + "", + ); + req = request(app); }); @@ -469,7 +474,7 @@ describe.each([ ); }); - it('should return "200" code code for the "GET" request and "Content-Length" to the file with unicode', async () => { + it('should return "200" code for the "GET" request and "Content-Length" to the file with unicode', async () => { const response = await req.get("/byte-length.html"); expect(response.statusCode).toEqual(200); @@ -482,6 +487,16 @@ describe.each([ ); }); + it('should return "200" code for the "GET" request and "Content-Length" of "0" when file is empty', async () => { + const response = await req.get("/empty-file.txt"); + + expect(response.statusCode).toEqual(200); + expect(response.headers["content-length"]).toEqual("0"); + expect(response.headers["content-type"]).toEqual( + "text/plain; charset=utf-8", + ); + }); + it('should return the "200" code for the "GET" request to the "image image.svg" file', async () => { const fileData = instance.context.outputFileSystem.readFileSync( path.resolve(outputPath, "image image.svg"),