readable[Symbol.asyncIterator]()
- 返回:<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); 如果循环通过 break、return 或 throw 终止,流将会被销毁。换句话说,对流进行迭代将会完全消耗该流。流会以大小等于 highWaterMark 选项的块读取。在上面的代码示例中,如果文件数据少于 64 KiB,由于没有为 fs.createReadStream() 提供 highWaterMark 选项,数据将会在一个单独的块中读取。
【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().】