流操作 ReadableStream

流操作

ReadableStream - Web API 接口参考 | MDN https://developer.mozilla.org/zh-CN/docs/Web/API/ReadableStream

ReadableStream

 

 

流操作API 中的ReadableStream 接口呈现了一个可读取的二进制流操作。Fetch API 通过 Response 的属性 body (en-US) 提供了一个具体的 ReadableStream 对象。

构造函数

ReadableStream()
创建并从给定的 Handler 返回一个可读流对象。

属性

ReadableStream.locked (en-US) 只读
locked 返回这个可读流是否被一个读取器锁定

方法

ReadableStream.cancel() (en-US)
取消读取流,读取方发出一个信号,表示对这束流失去兴趣。可以传入 reason 参数表示取消原因,这个原因将传回给调用方。
ReadableStream.getIterator()
创建一个异步的 ReadableStream 迭代器并将流锁定于其上。一旦流被锁定,其他读取器将不能读取它,直到它被释放。
ReadableStream.getReader()
创建一个读取器并将流锁定于其上。一旦流被锁定,其他读取器将不能读取它,直到它被释放。
ReadableStream.pipeThrough() (en-US)
提供将当前流管道输出到一个 transform 流或 writable/readable 流对的链式方法。
ReadableStream.pipeTo() (en-US)
将当前 ReadableStream 管道输出到给定的 WritableStream (en-US),并返回一个 promise,输出过程成功时返回 fulfilled,在发生错误时返回 rejected。
ReadableStream.tee() (en-US)
tee 方法(tee本意是将高尔夫球放置在球座上)tees 了可读流,返回包含两个ReadableStream实例分支的数组,每个元素接收了相同的传输数据。
ReadableStream[@@asyncIterator]()
getIterator 方法的别名。

示例

下面的例子,创建了一个智能的 Response 来流式化从别的资源处取得的HTML 片段。

它演示了 ReadableStream 与 Uint8Array (en-US) 的协同用法。

fetch("https://www.example.org/").then((response) => {
  const reader = response.body.getReader();
  const stream = new ReadableStream({
    start(controller) {
      // 下面的函数处理每个数据块
      function push() {
        // "done"是一个布尔型,"value"是一个Uint8Array
        reader.read().then(({ done, value }) => {
          // 判断是否还有可读的数据?
          if (done) {
            // 告诉浏览器已经结束数据发送
            controller.close();
            return;
          }

          // 取得数据并将它通过controller发送给浏览器
          controller.enqueue(value);
          push();
        });
      };

      push();
    }
  });

  return new Response(stream, { headers: { "Content-Type": "text/html" } });

 

ReadableStream

The ReadableStream interface of the Streams API represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object.

Constructor

ReadableStream()

Creates and returns a readable stream object from the given handlers.

Properties

ReadableStream.locked Read only

The locked getter returns whether or not the readable stream is locked to a reader.

Methods

ReadableStream.cancel()

Returns a Promise that resolves when the stream is canceled. Calling this method signals a loss of interest in the stream by a consumer. The supplied reason argument will be given to the underlying source, which may or may not use it.

ReadableStream.getReader()

Creates a reader and locks the stream to it. While the stream is locked, no other reader can be acquired until this one is released.

ReadableStream.pipeThrough()

Provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair.

ReadableStream.pipeTo()

Pipes the current ReadableStream to a given WritableStream and returns a Promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered.

ReadableStream.tee()

The tee method tees this readable stream, returning a two-element array containing the two resulting branches as new ReadableStream instances. Each of those streams receives the same incoming data.

Examples

 

Fetch stream

In the following example, an artificial Response is created to stream HTML fragments fetched from another resource to the browser.

It demonstrates the usage of a ReadableStream in combination with a Uint8Array.

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
  return new Response(stream, { headers: { "Content-Type": "text/html" } }).text();
})
.then(result => {
  // Do things with result
  console.log(result);
});

Async iterator to stream

Converting an (async) iterator to a readable stream:

function iteratorToStream(iterator) {
  return new ReadableStream({
    async pull(controller) {
      const { value, done } = await iterator.next();

      if (done) {
        controller.close();
      } else {
        controller.enqueue(value);
      }
    },
  });
}

This works with both async and non-async iterators.

 

 

Request.body - Web APIs | MDN https://developer.mozilla.org/en-US/docs/Web/API/Request/body

Request.body

The read-only body property of the Request interface contains a ReadableStream with the body contents that have been added to the request. Note that a request using the GET or HEAD method cannot have a body and null is return in these cases.

Syntax

request.body

Value

ReadableStream or null.

Examples

const request = new Request('/myEndpoint', {
  method: 'POST',
  body: 'Hello world'
});

request.body; // ReadableStream

 

posted @ 2022-02-21 17:40  papering  阅读(1221)  评论(0编辑  收藏  举报