denoland / deno

A modern runtime for JavaScript and TypeScript.
https://deno.com
MIT License
93.06k stars 5.14k forks source link

`node:fs/promises`: Neither `fd.read` nor `fd.write` honor the `position` argument #23707

Open Hexagon opened 1 week ago

Hexagon commented 1 week ago

Version: Deno 1.43.1

See this simple exmple, working in Node, but failing in Deno

import { open, access, writeFile, constants } from "node:fs/promises";

const FILENAME = "test.bin";

async function createFileIfNotExists() {
  try {
    // Attempt to access the file (check if it exists)
    await access(FILENAME, constants.F_OK);
  } catch (error) {
    // If the file doesn't exist, create an empty one
    if (error.code === 'ENOENT') {
      await writeFile(FILENAME, ''); 
      console.log('File created:', FILENAME);
    } else {
      throw error; // Handle other potential errors
    }
  }
}
async function modifyAndRead() {
    let fd
    try {
      fd = await open(FILENAME, "r+"); // r+ mode; best suitable for random access

      // Write "1" on position 100, etc
      // - This works in node.js, but Deno ignores the position, and always starts writing from zero
      for (let i = 0; i <= 30; i++) {
        const buffer = new Uint8Array([i]); // Create a buffer with value i (0-30)
        await fd.write(buffer, 0, 1, i + 100); // Write to file at offset i + 100 
      }

      // Read character by character from position 100
      // - This doesn't work at all in Deno, it always reads 0
      for (let i = 100; i <= 130; i++) {
        const buffer =  new Uint8Array(1); // Create a 1-byte buffer
        await fd.read(buffer, 0, 1, i);  // Read from file at offset i
        console.log(i, buffer.toString()); // Log the position and character
      }
    } catch (error) {
      console.error("Error occurred:", error);
    } finally {
      if (fd) fd.close(fd);
    }
  }

  await createFileIfNotExists();
  await modifyAndRead();