Course contentsShow
← JavaScript
Lesson 2036 of 2,72342. Iteration Protocols Deep DiveFree lesson

For-Await-Of with Readable Streams

Apply for-await-of to consume Node.js readable streams or web streams, processing chunks asynchronously.

For-Await-Of with Readable Streams

You'll learn how to use for-await-of to consume Node.js readable streams and web streams, processing data chunks asynchronously as they arrive.

The Core Idea

Readable streams (like file streams, HTTP responses, or socket connections) emit data in chunks over time. Instead of manually attaching event listeners (on('data'), on('end')), you can use for-await-of to iterate through these chunks in a clean, async/await style. Each iteration waits for the next chunk to arrive.

Think of it like reading a book page-by-page as someone hands you each page—you process one chunk at a time, waiting for the next to arrive.

Node.js Readable Streams

import { createReadStream } from 'fs';

async function processFile() {
  const stream = createReadStream('data.txt', { encoding: 'utf8' });
  
  for await (const chunk of stream) {
    console.log('Received chunk:', chunk.length, 'bytes');
    // Process each chunk as it arrives
  }
  
  console.log('Stream complete');
}

Web Streams (Fetch API)

async function fetchData() {
  const response = await fetch('https://example.com/large-file');
  const reader = response.body.getReader();
  
  // Convert to async iterable
  const stream = {
    async *[Symbol.asyncIterator]() {
      while (true) {
        const { done, value } = await reader.read();
        if (done) return;
        yield value;
      }
    }
  };
  
  for await (const chunk of stream) {
    console.log('Downloaded chunk:', chunk.byteLength);
  }
}

Why It Matters

No more callback spaghetti with .on() listeners. Handle backpressure naturally—the loop won't pull the next chunk until you're ready. Perfect for processing large files or network data without overwhelming memory.

Key Takeaway: for-await-of transforms stream consumption from event-driven callbacks into clean, linear async/await code that processes chunks sequentially as they arrive.