Stream errors and cleanup
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.
Handle a failed stage
import { Readable, Writable, Transform } from 'node:stream';import { pipeline, finished } from 'node:stream/promises';const source = Readable.from([1,2,3]);const check = new Transform({objectMode:true,transform(n,e,cb){if(n===2) cb(new Error('invalid item')); else cb(null,n);}});const sink = new Writable({objectMode:true,write(n,e,cb){cb();}});try { await pipeline(source,check,sink); } catch(e) { console.log(e.message, sink.destroyed); }Run:
node main.mjsExpected stdout:
invalid item trueExit status: 0. Expected stderr: empty.
How it works
An end event belongs to the readable side; finish concerns completed writes; close means an underlying resource was closed when that event applies. These signals are not interchangeable. The promise returned by pipeline rejects if a stage fails. In the first example, a rejected transform stops the copy. In the second, finished observes a writable that completes normally. Its cleanup option removes the listeners that finished attached; it does not close an arbitrary resource by itself.
Observe normal writable completion
import { Readable, Writable, Transform } from 'node:stream';import { pipeline, finished } from 'node:stream/promises';const sink = new Writable({write(c,e,cb){cb();}});const complete = finished(sink,{cleanup:true});sink.end('ok');await complete;console.log(sink.writableFinished);Run:
node main.mjsExpected stdout:
trueExit status: 0. Expected stderr: empty.
Common mistake
Calling pipe alone is not a complete error-management plan. Do not retry a destroyed stream object; create a fresh pipeline and consider whether partially written data must be removed.
Practice
Change the failing input from 2 to 9 and verify that the pipeline now completes. Consider how you would avoid committing a partial output file.
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
Stream errors and cleanup — knowledge check
Apply the concepts and predict the behavior taught in this lesson.
What should a caller do with pipeline() rejection?
Which signal indicates writable writes have completed?
What does finished({cleanup:true}) remove?