Skip to content

Commit 0f3e25e

Browse files
authored
fix: ContentLength incorrectly set for empty files (#1785)
1 parent d45f033 commit 0f3e25e

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

src/utils/compatibleAPI.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -267,7 +267,9 @@ async function send(req, res, filename, start, end, goNext, options) {
267267
start,
268268
end,
269269
});
270-
byteLength = end - start + 1;
270+
271+
// Handle files with zero bytes
272+
byteLength = end === 0 ? 0 : end - start + 1;
271273
} else {
272274
bufferOrStream = /** @type {import("fs").readFileSync} */ (
273275
options.outputFileSystem.readFileSync

test/middleware.test.js

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,11 @@ describe.each([
124124
"unknown",
125125
);
126126

127+
instance.context.outputFileSystem.writeFileSync(
128+
path.resolve(outputPath, "empty-file.txt"),
129+
"",
130+
);
131+
127132
req = request(app);
128133
});
129134

@@ -469,7 +474,7 @@ describe.each([
469474
);
470475
});
471476

472-
it('should return "200" code code for the "GET" request and "Content-Length" to the file with unicode', async () => {
477+
it('should return "200" code for the "GET" request and "Content-Length" to the file with unicode', async () => {
473478
const response = await req.get("/byte-length.html");
474479

475480
expect(response.statusCode).toEqual(200);
@@ -482,6 +487,16 @@ describe.each([
482487
);
483488
});
484489

490+
it('should return "200" code for the "GET" request and "Content-Length" of "0" when file is empty', async () => {
491+
const response = await req.get("/empty-file.txt");
492+
493+
expect(response.statusCode).toEqual(200);
494+
expect(response.headers["content-length"]).toEqual("0");
495+
expect(response.headers["content-type"]).toEqual(
496+
"text/plain; charset=utf-8",
497+
);
498+
});
499+
485500
it('should return the "200" code for the "GET" request to the "image image.svg" file', async () => {
486501
const fileData = instance.context.outputFileSystem.readFileSync(
487502
path.resolve(outputPath, "image image.svg"),

0 commit comments

Comments
 (0)