Skip to content

Commit

Permalink
feat(node/fs): Add a createReadStream method to the FileHandle class
Browse files Browse the repository at this point in the history
  • Loading branch information
nkaradzhov committed Jan 8, 2025
1 parent 1661ddd commit 98bc820
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
10 changes: 9 additions & 1 deletion ext/node/polyfills/internal/fs/handle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import { EventEmitter } from "node:events";
import { Buffer } from "node:buffer";
import { Mode, promises, read, write } from "node:fs";
import { createReadStream, Mode, promises, read, ReadStream, write } from "node:fs";
export type { BigIntStats, Stats } from "ext:deno_node/_fs/_fs_stat.ts";
import {
BinaryOptionsArgument,
Expand All @@ -15,6 +15,7 @@ import {
} from "ext:deno_node/_fs/_fs_common.ts";
import { ftruncatePromise } from "ext:deno_node/_fs/_fs_ftruncate.ts";
import { core } from "ext:core/mod.js";
import { CreateReadStreamOptions } from "node:fs/promises";

interface WriteResult {
bytesWritten: number;
Expand Down Expand Up @@ -148,10 +149,17 @@ export class FileHandle extends EventEmitter {
stat(options?: { bigint: boolean }): Promise<Stats | BigIntStats> {
return fsCall(promises.fstat, this, options);
}

chmod(mode: Mode): Promise<void> {
assertNotClosed(this, promises.chmod.name);
return promises.chmod(this.#path, mode);
}

createReadStream(options?: CreateReadStreamOptions): ReadStream {
assertNotClosed(this, createReadStream.name);
const opts = options as Omit<CreateReadStreamOptions, "encoding">;
return createReadStream(this.#path, opts);
}
}

function assertNotClosed(handle: FileHandle, syscall: string) {
Expand Down
33 changes: 33 additions & 0 deletions tests/unit_node/_fs/_fs_handle_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,3 +217,36 @@ Deno.test({
await fileHandle.close();
},
});

Deno.test(
"[node/fs filehandle.createReadStream] Create a read stream",
async function () {
const fileHandle = await fs.open(testData);
const stream = fileHandle.createReadStream();
const fileSize = (await fileHandle.stat()).size;

assertEquals(stream.bytesRead, 0);
assertEquals(stream.readable, true);

let bytesRead = 0;

stream.on("open", () => assertEquals(stream.bytesRead, 0));

stream.on("data", (data) => {
assertEquals(data instanceof Buffer, true);
assertEquals((data as Buffer).byteOffset % 8, 0);
bytesRead += data.length;
assertEquals(stream.bytesRead, bytesRead);
});

stream.on("end", () => {
assertEquals(stream.bytesRead, fileSize);
assertEquals(bytesRead, fileSize);
});

await new Promise((resolve) => {
stream.close(resolve);
});
await fileHandle.close();
},
);

0 comments on commit 98bc820

Please sign in to comment.