Skip to content

Commit

Permalink
fix(util-body-length-node): support fd.createReadStream (#3385)
Browse files Browse the repository at this point in the history
  • Loading branch information
trivikr committed Mar 8, 2022
1 parent d220242 commit 88f8cc2
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 9 deletions.
26 changes: 18 additions & 8 deletions packages/util-body-length-node/src/calculateBodyLength.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createReadStream, lstatSync } from "fs";
import { createReadStream, lstatSync, promises } from "fs";

import { calculateBodyLength } from "./calculateBodyLength";

Expand Down Expand Up @@ -38,17 +38,27 @@ describe(calculateBodyLength.name, () => {
expect(calculateBodyLength(view)).toEqual(1);
});

describe("should handle stream created using fs.createReadStream", () => {
describe("fs.ReadStream", () => {
const fileSize = lstatSync(__filename).size;

it("when path is a string", () => {
const fsReadStream = createReadStream(__filename);
expect(calculateBodyLength(fsReadStream)).toEqual(fileSize);
describe("should handle stream created using fs.createReadStream", () => {
it("when path is a string", () => {
const fsReadStream = createReadStream(__filename);
expect(calculateBodyLength(fsReadStream)).toEqual(fileSize);
});

it("when path is a Buffer", () => {
const fsReadStream = createReadStream(Buffer.from(__filename));
expect(calculateBodyLength(fsReadStream)).toEqual(fileSize);
});
});

it("when path is a Buffer", () => {
const fsReadStream = createReadStream(Buffer.from(__filename));
expect(calculateBodyLength(fsReadStream)).toEqual(fileSize);
it("should handle stream created using fd.createReadStream", async () => {
const fd = await promises.open(__filename, "r");
if ((fd as any).createReadStream) {
const fdReadStream = (fd as any).createReadStream();
expect(calculateBodyLength(fdReadStream)).toEqual(fileSize);
}
});
});
});
5 changes: 4 additions & 1 deletion packages/util-body-length-node/src/calculateBodyLength.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { lstatSync } from "fs";
import { fstatSync, lstatSync } from "fs";

export const calculateBodyLength = (body: any): number | undefined => {
if (!body) {
Expand All @@ -14,5 +14,8 @@ export const calculateBodyLength = (body: any): number | undefined => {
} else if (typeof body.path === "string" || Buffer.isBuffer(body.path)) {
// handles fs readable streams
return lstatSync(body.path).size;
} else if (typeof body.fd === "number") {
// handles fd readable streams
return fstatSync(body.fd).size;
}
};

0 comments on commit 88f8cc2

Please sign in to comment.