javascriptdeno

Deno file.read with file.write, size not matching


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);
    }
  }

Solution

  • 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);