Advertisement
Advanced JavaScript, Async Iterators & Streams

How do you convert a Node.js Readable stream into an async iterable?

Short answer

Modern Node.js Readable streams already implement Symbol.asyncIterator directly, so you can for-await-of over them without any extra wrapping.

Save JavaScript mock interview
Advertisement
AModel answer
Modern Node.js Readable streams already implement Symbol.asyncIterator directly, so you can for-await-of over them without any extra wrapping.
const fs = require('fs');
async function readFile() {
  const stream = fs.createReadStream('data.txt');
  for await (const chunk of stream) {
    console.log(chunk.toString());
  }
}
Real-world example
Processing a large log file line-by-line without loading the whole file into memory.
Likely follow-ups
  • How would you handle backpressure when the consumer is slower than the source?
Related topics