DAILY DOCDAILY DOC
Rust
Node
Notes
Ubuntu
Leetcode
  • it-tools
  • excalidraw
  • linux-command
Rust
Node
Notes
Ubuntu
Leetcode
  • it-tools
  • excalidraw
  • linux-command
  • BFC 块级格式化上下文
  • Note
  • WebAssembly
  • public api
  • 位运算
  • bitwise operator
  • css实现隐藏效果
  • css snippets
  • 抖音点赞
  • js 相等判断
  • fetch ReadableStream
  • git
  • Github Actions 工作流
  • google search
  • RPC vs HTTP
  • gravatar
  • hhkb
  • Init project
  • input 文件上传
  • mac

    • Mac 使用技巧
    • alfred
    • mac shortcuts
    • shortcuts text edit
    • mac 修改host
  • 微前端
  • mock
  • nginx dump
  • nginx
  • NirCmd
  • npm
  • Operator Precedence
  • package.json
  • url query 解析
  • pnpm
  • JavaScript Precise countdown
  • react 模版
  • regexp
  • setup web development
  • telegram

    • telegram bot
  • timeFunction ease
  • 视频裁剪
  • vscode

    • vscode 高级指南
    • bracketPairs
    • jsconfig.json
    • vscode pipe into code
    • social project
    • vscode tasks
  • draggable resizable
  • windows 激活
  • 前端截图实现
  • 文本配音 富文本实现
  • 图片处理
  • 前端坐标
  • 定时任务
  • work efficient
  • 微信小程序动画实现方案
  • 排列组合
  • 数列
  • 语音驱动文字
  • 浏览器
  • 状态管理
  • 移动盒子
  • 移动端开发常用snippets
  • 设计模式
  • web performance

fetch ReadableStream

递归

details
fetch('xxxx')
  .then(res => res.body)
  .then(stream => {
    const reader = stream.getReader();
    console.log('reader', reader);
    // reader.read().then(res => {
    //   console.log(res);
    // });
    let count = 0;
    const recursiveRead = () => {
      reader.read().then(res => {
        count += 1;
        console.log(res);
        if (!res.done) {
          return recursiveRead();
        }
        console.log('count', count);
      });
    };
    return recursiveRead();
  });

Async Iterator

details
fetch('xxxx')
  .then(res => res.body)
  .then(async stream => {
    const reader = stream.getReader();
    let asyncIterator = {
      [Symbol.asyncIterator]() {
        return {
          next() {
            return reader.read();
          },
        };
      },
    };

    for await (const chunk of asyncIterator) {
      console.log(chunk);
    }
  });

Generator

details
fetch('xxx')
  .then(res => res.body)
  .then(async stream => {
    async function* chunkGenerator(stream) {
      const reader = stream.getReader();
      try {
        while (true) {
          const { value, done } = await reader.read();
          if (done) {
            break;
          }
          yield value;
        }
      } catch (err) {
        console.log('err', err);
      } finally {
        reader.releaseLock();
      }
    }

    for await (const chunk of chunkGenerator(stream)) {
      console.log(chunk);
    }
  });

TextDecoder 解码

details
import { TextDecoder } from 'util';

fetch('xxx')
  .then(res => res.body)
  .then(async stream => {
    const decoder = new TextDecoder();
    // async function* chunkGenerator(stream) {
    //   const reader = stream.getReader();
    //   try {
    //     while (true) {
    //       const { value, done } = await reader.read();
    //       if (done) {
    //         break;
    //       }
    //       yield value;
    //     }
    //   } catch (err) {
    //     console.log('err', err);
    //   } finally {
    //     reader.releaseLock();
    //   }
    // }

    for await (const chunk of chunkGenerator(stream)) {
      console.log(chunk, decoder.decode(chunk, { stream: true }));
    }
  });

pipe stream

details
fetch('https://www.example.org')
  .then((response) => response.body)
  .then((rb) => {
    const reader = rb.getReader();

    return new ReadableStream({
      start(controller) {
        // The following function handles each data chunk
        function push() {
          // "done" is a Boolean and value a "Uint8Array"
          reader.read().then(({ done, value }) => {
            // If there is no more data to read
            if (done) {
              console.log('done', done);
              controller.close();
              return;
            }
            // Get the data and send it to the browser via the controller
            controller.enqueue(value);
            // Check chunks by logging to the console
            console.log(done, value);
            push();
          });
        }

        push();
      },
    });
  })
  .then((stream) =>
    // Respond with our stream
    new Response(stream, { headers: { 'Content-Type': 'text/html' } }).text()
  )
  .then((result) => {
    // Do things with result
    console.log(result);
  });

Refer

  • ReadableStream
Last Updated:
Contributors: rosendo
Prev
js 相等判断
Next
git