Skip to content

Commit

Permalink
fix(util-body-length-node): calculateBodyLength for Readable stream w…
Browse files Browse the repository at this point in the history
…ith range

A ReadStream created with createReadStream(file, {start: 0, end: 0}) would not be detected by this function, or would falsly just use the size of the original file at body.path. This uses the end and start numbers if present, both are inclusive so 1 is added.

Inclusive according to: https://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options
  • Loading branch information
pingiun committed Aug 7, 2021
1 parent 30831c7 commit 98f684d
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
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

0 comments on commit 98f684d

Please sign in to comment.