Skip to content

FileHandle.read does not respect length parameter with Uint8Array #25086

@acrois

Description

@acrois

Version: Deno 1.45.5

Code:

import { assert } from "https://deno.land/[email protected]/assert/assert.ts";
import { open, unlink, writeFile } from "node:fs/promises";

Deno.test("fs: FileHandle.read() respects length parameter with Uint8Array", async () => {
  // Create a file with some sample data
  const filename = "example.bin";
  const array = new Uint8Array(256);
  for (let i = 0; i < 256; i++) {
    array[i] = i;
  }
  await writeFile(filename, array);

  // Open the file for reading
  const fileHandle = await open(filename, "r");

  // Test reading a portion of the file
  // NOTE: it is important that the array we are reading into is greater than our read length
  //       as it will often be larger in the case of reading a file in chunks.
  const readArray = new Uint8Array(2048);

  const readLength = 20;
  const readOffset = 100;
  const writeOffset = 0;

  const { bytesRead } = await fileHandle.read(
    readArray,
    writeOffset,
    readLength,
    readOffset,
  );

  assert(
    bytesRead === readLength,
    `Expected ${readLength} but got ${bytesRead}`,
  );

  for (let i = writeOffset; i < readLength; i++) {
    assert(readArray[i] === readOffset + i, "Correct data");
  }

  // Close the file handle
  await fileHandle.close();

  // Remove the test file
  await unlink(filename);
});

Test:

deno test --allow-read --allow-write

Result:

error: AssertionError: Expected 20 but got 156

Problematic:
https://github.com/denoland/deno/blob/main/ext/node/polyfills/internal/fs/handle.ts#L51-L64

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions