LoginSignup
5
6

More than 5 years have passed since last update.

WHATWG Streams の Stream と Pipe chain

Posted at

概要

WHATWG Streams のことを何回かに分けて書く。Kyoto.js #11 の『 WHATWG Streams をためした 』という発表のために調べたものだ。発表だけで終わらせるのはもったいないので、再整理して共有する。

今回は次の 3 つを書く。

  • WHATWG Streams の提供する Stream クラス
  • それらの Stream でつくる Pipe chain
  • Pipe chain を流れる chunk

Stream クラスについては概要に留め、それぞれの詳細は別途記載する。

3 つの Stream クラス

WHATWG Streams は次の 3 つの Streams クラスを提供している。

  1. ReadableStream
  2. WritableStream
  3. TransformStream

今回はあくまでも概要だけを書く。

1. ReadableStream

  • 読み取りのための Stream
  • Source から読んだデータを内部キューにためる
// イメージ
class ReadableStream {
  constructor(underlyingSource: Source, options?: ReadableStreamOptions);

  get locked(): boolean;

  cancel(reason: any): Promise<void>;
  getReader(): Reader;
  pipeThrough(
    transform: TransformStream, options?: PipeToOptions
  ): ReadableStream;
  pipeTo(
    writable: WritableStream, options?: PipeToOptions
  ): Promise<void>;
  tee(): [ReadableStream, ReadableStream];
}

2. WritableStream

  • 書き込みのための Stream
  • Sink に書くデータを内部キューにためる
// イメージ
class WritableStream {
  constructor(underlyingSink: Sink, options?: WritableStreamOptions);

  get locked(): boolean;

  abort(reason: any): Promise<void>;
  getWriter(): Writer;
}

3. TransformStream

  • 変換のための Stream
  • ReadableStream と WritableStream をそれぞれ readable / writable というプロパティで提供するオブジェクト
  • まだ仕様にない
class TransformStream {
  constructor(transformer: Transformer);
  get readable(): ReadableStream;
  get writable(): WritableStream;
}

Pipe chain をつくる

  • 3 種の Stream を pipe する (= pipe chain をつくる)
    • RS -(pipe)-> WS
    • RS -(pipe)-> TS -(pipe)-> ... -(pipe)-> WS
    • RS -(pipe)-> WS + RS -(pipe)-> WS
  • pipe chain を chunk が流れる
    • chunk は RS / WS が読み書きするデータの単位
const data = [1, 2, 3];
new ReadableStream({
  pull(controller) {
    const chunk = data.shift();
    controller.enqueue(chunk); // 1, 2, 3
  }
})
  .pipeThrough(new TransformStream({
    transform(chunk, controller) {
      controller.enqueue(chunk * 2);
    }
  }))
  .pipeTo(new WritableStream({
    write(chunk) {
      console.log(chunk); // 2, 4, 6
    }
  }));

参考

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6