ReadableStream.getReader()

翻译不完整。 请帮助我们翻译这篇文章!

使用ReadableStream接口的getReader() 方法创建一个reader,并将流锁定。只有当前reader将流释放后,其他reader才能使用。

语法

var reader = readableStreamInstance.getReader({mode});

参数

{mode}- 可选参数
具有 mode参数的对象,值为  DOMString类型 ,用来指定要创建的阅读器的类型。其值可以是:

返回值

ReadableStreamDefaultReader 类型或ReadableStreamBYOBReader 类型 实例, 取决于 mode 值.

错误

RangeError——范围错误
提供的 mode值 既不是 byob也不是  undefined
TypeError——类型错误
尝试创建阅读器的流不是 ReadableStream类型

例子

下面是个简单的例子, 在读取ReadableStream前,使用 getReader()创建一个ReadableStreamDefaultReader 。(查看全部代码 Simple random stream example ). 按顺序读取每个块,并传递给UI, 当整个流被读取完毕后, 从递归方法中退出,并在UI的另一部分输出整个流。

function fetchStream() {
  const reader = stream.getReader();
  let charsReceived = 0;

  // read() 返回了一个promise
  // 当数据被接收时resolve
  reader.read().then(function processText({ done, value }) {
    // Result对象包含了两个属性:
    // done  - 当stream传完所有数据时则变成true
    // value - 数据片段。当done不为true时永远为undefined
    if (done) {
      console.log("Stream complete");
      para.textContent = value;
      return;
    }

    // value for fetch streams is a Uint8Array
    charsReceived += value.length;
    const chunk = value;
    let listItem = document.createElement('li');
    listItem.textContent = 'Received ' + charsReceived + ' characters so far. Current chunk = ' + chunk;
    list2.appendChild(listItem);

    result += chunk;

    // 再次调用这个函数以读取更多数据
    return reader.read().then(processText);
  });
}

说明

Specification Status(状态) Comment(备注)
Streams
getReader()
Living Standard Initial definition.

浏览器兼容

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
getReader
Experimental
Chrome Full support 43Edge Full support 14Firefox Full support 65
Full support 65
Full support 57
Disabled
Disabled From version 57: this feature is behind the dom.streams.enabled preference (needs to be set to true) and the javascript.options.streams preference (needs to be set to true). To change preferences in Firefox, visit about:config.
IE No support NoOpera Full support 30Safari Full support 10.1WebView Android Full support 43Chrome Android Full support 43Firefox Android Full support 65
Full support 65
Full support 57
Disabled
Disabled From version 57: this feature is behind the dom.streams.enabled preference (needs to be set to true) and the javascript.options.streams preference (needs to be set to true). To change preferences in Firefox, visit about:config.
Opera Android Full support 30Safari iOS Full support 10.3Samsung Internet Android Full support 4.0

Legend

Full support  
Full support
No support  
No support
Experimental. Expect behavior to change in the future.
Experimental. Expect behavior to change in the future.
User must explicitly enable this feature.
User must explicitly enable this feature.