Readable and writable streams
Local practice: Node.js 22.16.0 on Linux x64; proposed 26.13.1 baseline remains untested. Save each example separately as main.mjs in a disposable directory. No packages or external services required. HTTP examples bind only to loopback and shut down after a finite scenario. Static Node.js code, not verified ByteMind execution.
Read byte chunks
import { Readable, Writable, Transform } from 'node:stream';import { pipeline, finished } from 'node:stream/promises';const source = Readable.from([Buffer.from('bo'), Buffer.from('ok')], {objectMode:false});let text = '';for await (const chunk of source) text += chunk.toString('ascii');console.log(text);Run:
node main.mjsExpected stdout:
bookExit status: 0. Expected stderr: empty.
How it works
A chunk is not necessarily a record or line. Byte streams carry bytes or strings; object-mode streams carry JavaScript values other than null. Readable.from creates a readable from an iterable and defaults to object mode. Async iteration requests data as it becomes available. The first example collects two tiny byte chunks; the second sends three object-mode values to a receiver. The collector is only appropriate for bounded data. For large inputs, write results incrementally instead.
Deliver objects to a writable
import { Readable, Writable, Transform } from 'node:stream';import { pipeline, finished } from 'node:stream/promises';let total = 0;const sink = new Writable({objectMode:true, write(n, enc, done) { total += n; done(); }});await pipeline(Readable.from([2, 3, 5]), sink);console.log(total, sink.writableFinished);Run:
node main.mjsExpected stdout:
10 trueExit status: 0. Expected stderr: empty.
Common mistake
Do not assume that one chunk equals one line or that object-mode highWaterMark counts bytes. Avoid mixing data listeners and async iteration on the same stream unless you deliberately manage consumption.
Practice
Change the three numeric inputs to an empty array, then to [4, 5]. Predict and check the receiver total.
Further reading: Authoritative source 1. Internal reference routes remain proposed until repository discovery.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Readable and writable streams — knowledge check
Apply the concepts and predict the behavior taught in this lesson.
Which stream supplies chunks?
In object mode, what does highWaterMark count?
What is true about chunk boundaries?