readable[Symbol.asyncIterator]()


const fs = require('fs');

async function print(readable) {
  readable.setEncoding('utf8');
  let data = '';
  for await (const chunk of readable) {
    data += chunk;
  }
  console.log(data);
}

print(fs.createReadStream('file')).catch(console.error);

如果循环以 breakthrow 终止,则流将被销毁。 换句话说,遍历流将完全消费流。 流将以大小等于 highWaterMark 选项的块读取。 在上面的代码示例中,如果文件的数据少于 64KB,则数据将位于单个块中,因为没有为 fs.createReadStream() 提供 highWaterMark 选项。

const fs = require('fs');

async function print(readable) {
  readable.setEncoding('utf8');
  let data = '';
  for await (const chunk of readable) {
    data += chunk;
  }
  console.log(data);
}

print(fs.createReadStream('file')).catch(console.error);

If the loop terminates with a break or a throw, the stream will be destroyed. In other terms, iterating over a stream will consume the stream fully. The stream will be read in chunks of size equal to the highWaterMark option. In the code example above, data will be in a single chunk if the file has less then 64KB of data because no highWaterMark option is provided to fs.createReadStream().