GoogleChromeLabs / browser-fs-access

File System Access API with legacy fallback in the browser
https://googlechromelabs.github.io/browser-fs-access/demo/
Apache License 2.0
1.38k stars 84 forks source link

Reading a file using ReadableStream #76

Closed Urmeli0815 closed 2 years ago

Urmeli0815 commented 2 years ago

I try the following to read a picked file in chunks:

const options: FirstFileOpenOptions<false> = {
    startIn: 'desktop',
    id: 'sendFile'
};

const file = await fileOpen(options);

const logChunks = async (readable: NodeJS.ReadableStream) => {
    for await (const chunk of readable) {
        console.log("Chunk: " + chunk.length);
    }
};

let stream = file.stream();
logChunks(stream);

This doesn't work neither in Edge nor in Firefox. file.stream() returns a ReadableStream object but it doesn't seem to have any methods.

I also tried to use a variant with stream.on('data', ...) but this is also undefined.

Am I doing something totally wrong or is this usage just not supported yet by browsers?

tomayac commented 2 years ago

You're close, but there's a missing part:

const reader = file.stream().getReader();
while (true) {
  const { done, value } = await reader.read();
  if (done) {
    console.log('The stream is done.');
    break;
  }
  console.log('Just read a chunk:', value);
}

See my [article](https://web.dev/streams/#the-getreader()-and-read()-methods) for details.

Urmeli0815 commented 2 years ago

Thank you very much for the fast feedback, I'll try that.