read() 方法在 ReadableStreamDefaultReader interface returns a promise providing access to the next chunk in the stream's internal queue.

句法

var promise = readableStreamDefaultReader.read();
					

参数

None.

返回值

A Promise , which fulfills/rejects with a result depending on the state of the stream. The different possibilities are as follows:

  • If a chunk is available, the promise will be fulfilled with an object of the form { value: theChunk, done: false } .
  • If the stream becomes closed, the promise will be fulfilled with an object of the form { value: undefined, done: true } .
  • If the stream becomes errored, the promise will be rejected with the relevant error.

异常

TypeError
The source object is not a ReadableStreamDefaultReader , or the stream has no owner.

范例

Example 1 - simple example

This example shows the basic API usage, but doesn't try to deal with complications like stream chunks not ending on line boundaries for example.

In this example stream is a previously-created custom ReadableStream . It is read using a ReadableStreamDefaultReader created using getReader() . (see our Simple random stream example for the full code). Each chunk is read sequentially and output to the UI as an array of UTF-8 bytes, until the stream has finished being read, at which point we return out of the recursive function and print the entire stream to another part of the UI.

function fetchStream() {
  const reader = stream.getReader();
  let charsReceived = 0;
  // read() returns a promise that resolves
  // when a value has been received
  reader.read().then(function processText({ done, value }) {
    // Result objects contain two properties:
    // done  - true if the stream has already given you all its data.
    // value - some data. Always undefined when done is true.
    if (done) {
      console.log("Stream complete");
      para.textContent = result;
      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;
    // Read some more, and call this function again
    return reader.read().then(processText);
  });
}
					

Example 2 - handling text line by line

This example shows how you might fetch a text file and handle it as a stream of text lines. It deals with stream chunks not ending on line boundaries and converting from Uint8Array to strings.

async function* makeTextFileLineIterator(fileURL) {
  const utf8Decoder = new TextDecoder("utf-8");
  let response = await fetch(fileURL);
  let reader = response.body.getReader();
  let {value: chunk, done: readerDone} = await reader.read();
  chunk = chunk ? utf8Decoder.decode(chunk) : "";
  let re = /\r\n|\n|\r/gm;
  let startIndex = 0;
  let result;
  for (;;) {
    let result = re.exec(chunk);
    if (!result) {
      if (readerDone) {
        break;
      }
      let remainder = chunk.substr(startIndex);
      ({value: chunk, done: readerDone} = await reader.read());
      chunk = remainder + (chunk ? utf8Decoder.decode(chunk) : "");
      startIndex = re.lastIndex = 0;
      continue;
    }
    yield chunk.substring(startIndex, result.index);
    startIndex = re.lastIndex;
  }
  if (startIndex < chunk.length) {
    // last line didn't end in a newline char
    yield chunk.substr(startIndex);
  }
}
for await (let line of makeTextFileLineIterator(urlOfFile)) {
  processLine(line);
}
					

规范

规范 状态 注释

The definition of 'read()' in that specification.
实时标准 初始定义。

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
read Chrome ? Edge ? Firefox 65
65
57 Disabled
Disabled From version 57: this feature is behind the dom.streams.enabled preference (needs to be set to true ) 和 preference (needs to be set to ). To change preferences in Firefox, visit about:config.
IE ? Opera ? Safari ? WebView Android ? Chrome Android ? Firefox Android 65
65
57 Disabled
Disabled From version 57: this feature is behind the dom.streams.enabled preference (needs to be set to true ) 和 preference (needs to be set to ). To change preferences in Firefox, visit about:config.
Opera Android ? Safari iOS ? Samsung Internet Android ?

图例

完整支持

完整支持

兼容性未知 ?

兼容性未知

实验。期望将来行为有所改变。

实验。期望将来行为有所改变。

用户必须明确启用此特征。

用户必须明确启用此特征。

元数据

  • 最后修改: