Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(util-body-length-node): calculateBodyLength for Readable stream with range #2637

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions packages/util-body-length-node/src/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
import { promises } from 'fs';
import { createReadStream, writeFile } from "fs-extra";
import * as os from "os";
import * as path from "path";

import { calculateBodyLength } from "./";

const arrayBuffer = new ArrayBuffer(1);
Expand Down Expand Up @@ -28,4 +33,28 @@ describe("caclulateBodyLength", () => {
it("should handle DataView inputs", () => {
expect(calculateBodyLength(view)).toEqual(1);
});

it("should handle a Readable from a file", async () => {
const tmpDir = await promises.mkdtemp(path.join(os.tmpdir(), 'test1-'));
const filePath = path.join(tmpDir, "foo");
await writeFile(filePath, "foo");
const handle = await promises.open(filePath, 'r');
const readStream = createReadStream(filePath, {fd: handle.fd});
expect(calculateBodyLength(readStream)).toEqual(3);
readStream.destroy();
await promises.unlink(filePath);
await promises.rmdir(tmpDir);
});

it("should handle Readable with start end from a file", async () => {
const tmpDir = await promises.mkdtemp(path.join(os.tmpdir(), 'test2-'));
const filePath = path.join(tmpDir, "foo");
await writeFile(filePath, "foo");
const handle = await promises.open(filePath, 'r');
const readStream = createReadStream(filePath, {fd: handle.fd, start: 1, end: 1});
expect(calculateBodyLength(readStream)).toEqual(1);
readStream.destroy();
await promises.unlink(filePath);
await promises.rmdir(tmpDir);
});
});
2 changes: 2 additions & 0 deletions packages/util-body-length-node/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ export function calculateBodyLength(body: any): number | undefined {
return body.byteLength;
} else if (typeof body.size === "number") {
return body.size;
} else if (typeof body.start === "number" && typeof body.end === "number") {
return body.end + 1 - body.start;
} else if (typeof body.path === "string") {
// handles fs readable streams
return lstatSync(body.path).size;
Expand Down