js: TransformStream 浏览器上的流转换

class UpperCaseTransformStream {
  constructor() {
    return new TransformStream({
      transform(chunk, controller) {
        controller.enqueue(chunk.toUpperCase());
      },
    });
  }
}

(async () => {
  const response = await fetch("/index.js");
  const readableStream = response.body
    .pipeThrough(new TextDecoderStream()) // 将 uint8 转换为 text
    .pipeThrough(new UpperCaseTransformStream());

  const reader = readableStream.getReader();
  let out = "";
  while (true) {
    const { done, value } = await reader.read();
    if (done) {
      break;
    }
    out += value;
  }
  console.assert(out === 'CONSOLE.LOG(THIS);');
})();

See also:

posted @ 2022-07-28 09:53  Ajanuw  阅读(368)  评论(0编辑  收藏  举报