readable[Symbol.asyncIterator]()


const fs = require('node: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);

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

const fs = require('node: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, return, 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 64 KiB of data because no highWaterMark option is provided to fs.createReadStream().