Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท Streams and readline

Async iteration of Node.js streams

Reference for async iteration of Node.js readable streams: for await...of, readable.iterator() options, error handling, early exit and backpressure.

Every readable stream is an async iterable. A for await...of loop pulls one chunk at a time, waits for your loop body to finish before pulling the next one, and ends when the stream ends. It is usually the clearest way to consume a stream, because backpressure, errors and cleanup come for free.

readable.iterator([options]) is the explicit form of the same thing. It returns the async iterator, and it lets you decide whether leaving the loop early destroys the stream.

NODE
for await (const chunk of readable) {
  // handle chunk
}

Try it

Node.js Looping over a stream

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Breaking out early and errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
for await (const chunk of readable) { }
readable.iterator([options]): AsyncIterator
Name Description
options.destroyOnReturn Boolean, default true. When false, leaving the loop early (break, return, throw) does not destroy the stream, so you can keep reading it afterwards.

Chunk type: Buffer for byte streams (strings if setEncoding() was used), arbitrary values in object mode.

Errors: if the stream emits 'error' or is destroyed with an error, the loop throws that error at the next iteration. A stream destroyed without an error ends the loop with ERR_STREAM_PREMATURE_CLOSE.

Usage notes

  • Chunks arrive one at a time, in order. The stream is not read ahead beyond its normal buffer, so a slow loop body slows down the producer.
  • A normal end destroys the stream (with autoDestroy), and so does break by default.
  • Do not attach 'data' listeners to a stream you are iterating; the two consumption styles conflict.
  • A stream can be iterated only once from the start. After a loop finishes, nothing is left to read.
  • Chunk boundaries are arbitrary for byte streams. To process lines or records, join chunks yourself or use readline (readline.createInterface({ input }) is also async iterable).
  • Overhead is slightly higher than a 'data' handler, which only matters for very hot paths with millions of tiny chunks.
  • Use stream.pipeline() with an async function as the last stage when the loop is the final consumer of a chain.