javascript - Deno file.read with file.write, size not matching - Stack Overflow

admin2025-04-20  0

I am having some issue with write files in Deno

The resulting files are damanged

The code is very simple, it's just reads from a file and writes to another:

  let bytesRead: number | null = -1;
  while(bytesRead !== null){
    const buf = new Uint8Array(5 * 1_000_000);
    bytesRead = await infh.read(buf)
    if(bytesRead !== null){
      await outfh.write(buf);
    }
  }

I am having some issue with write files in Deno

The resulting files are damanged

The code is very simple, it's just reads from a file and writes to another:

  let bytesRead: number | null = -1;
  while(bytesRead !== null){
    const buf = new Uint8Array(5 * 1_000_000);
    bytesRead = await infh.read(buf)
    if(bytesRead !== null){
      await outfh.write(buf);
    }
  }
Share Improve this question asked Mar 3 at 17:24 AlexAlex 66.2k185 gold badges460 silver badges651 bronze badges 2
  • in what way are the resulting files "damaged"? assuming infh.read(buf) is this you may want to read what is returned by that method (I assume Deno returns the same result - can't be bothered reading Deno documentation) – Bravo Commented Mar 3 at 20:53
  • deno does not return the buf, it only returns the number of bytes read. For some reason the resulting file is larger than the input file.. – Alex Commented Mar 4 at 10:44
Add a comment  | 

1 Answer 1

Reset to default 1

The Deno docs make it clear — for both the read and write methods on an instance of Deno.FsFile:

It is not guaranteed that the full buffer will be read/written in a single call.


The idiomatic approach for copying data from one instance to another is to pipe the ReadableStream of the input file to the WritableStream of the output file:

// declare let sourceFile: Deno.FsFile;
// declare let destinationFile: Deno.FsFile;

await sourceFile.readable.pipeTo(destinationFile.writable);
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745081122a283863.html

最新回复(0)