Skip to content

Commit

Permalink
fix: ContentLength incorrectly set for empty files
Browse files Browse the repository at this point in the history
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`.
  • Loading branch information
alan-agius4 committed Mar 21, 2024
1 parent d45f033 commit 4538591
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
4 changes: 3 additions & 1 deletion src/utils/compatibleAPI.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 16 additions & 1 deletion test/middleware.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,11 @@ describe.each([
"unknown",
);

instance.context.outputFileSystem.writeFileSync(
path.resolve(outputPath, "empty-file.txt"),
"",
);

req = request(app);
});

Expand Down Expand Up @@ -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);
Expand All @@ -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"),
Expand Down

0 comments on commit 4538591

Please sign in to comment.