【问题标题】:How to limit the size of each read from a ReadableStream如何限制从 ReadableStream 中每次读取的大小
【发布时间】:2022-06-15 23:32:35
【问题描述】:

我正在使用 HTML 文件输入从我的设备存储中访问一个文件,然后我将该文件作为流读取。

  • 是否有任何内置方法可以将每次读取的长度限制为特定的字节数。
const stream = myFile.stream() 
const reader = stream.getReader();

//actually I use this each time I want to read more data from the stream
reader.read().then(function({ done, value }) { 
  
    const bufferSizeInBytes = value.length //  I want to limit this to 1000 bytes as max value
   
    })

另一个让我困惑的问题是,为什么每次读取时缓冲区的大小都不同,这取决于可用内存或 cpu 还是它实际上是如何工作的?如果它取决于内存,我们将能够在一次读取中读取整个流,因为文件在 100 mb 左右,我的可用内存在 6GB 左右,但实际上它需要多次读取,这让我认为内存不是此操作背后的唯一因素。

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript streaming


    【解决方案1】:

    不,你目前无法控制默认文件流的reader chunk大小,你可以尝试将其转换为ByteStream,然后使用stream.getReader({ mode: 'byob' })获取BYOB reader来控制读取大小限制。

    更多信息:https://web.dev/streams/

    【讨论】:

      【解决方案2】:

      一种方法是创建一个中间的 ReadableStream ,它将有一个缓冲区,一旦缓冲区超过所需的chunkSize 然后入队(或者如果我们在最后一部分,然后只剩下一个

      像这样:

        const reader = readable.getReader();
        const chunkSize = 1 * 1024 * 1024 // 1MB
      
        let buffer: Uint8Array;
      
        const readableWithDefinedChunks = new ReadableStream({
          async pull(controller) {
            let fulfilledChunkQuota = false;
      
            while (!fulfilledChunkQuota) {
              const status = await reader.read();
      
              if (!status.done) {
                const chunk = status.value;
                buffer = new Uint8Array([...(buffer || []), ...chunk]);
      
                while (buffer.byteLength >= chunkSize) {
                  const chunkToSend = buffer.slice(0, chunkSize);
                  controller.enqueue(chunkToSend);
                  buffer = new Uint8Array([...buffer.slice(chunkSize)]);
                  fulfilledChunkQuota = true;
                }
              }
              if (status.done) {
                fulfilledChunkQuota = true;
                if (buffer.byteLength > 0) {
                  controller.enqueue(buffer);
                }
                controller.close();
              }
            }
          },
        });
      

      【讨论】:

        猜你喜欢
        • 2010-11-17
        • 1970-01-01
        • 1970-01-01
        • 2014-11-03
        • 1970-01-01
        • 1970-01-01
        • 2019-02-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多