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,数据将会在一个块中,因为没有提供 highWaterMark 选项给 fs.createReadStream()。
🌐 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 than 64 KiB of data because no highWaterMark option is provided to
fs.createReadStream().