Node.js stream events at a glance
Node.js streams are EventEmitter instances, and most of the control flow you write around them is driven by events rather than return values. Knowing exactly when data, end, drain, finish and close fire — and on which kind of stream — is what separates a leaky pipe from a robust one. This reference lists every standard stream event, the stream types that emit it, and the precise condition that triggers it.
How it works
Streams come in four base shapes. Readable streams produce data and emit data, readable, end, close and error. Writable streams consume data and emit drain, finish, pipe, unpipe, close and error. Duplex streams (like TCP sockets) are independent read and write sides, so they emit the union of both. Transform streams are Duplex streams whose output is a function of their input, so they additionally surface the lifecycle around _transform/_flush.
The two events that encode backpressure are drain and the boolean return of write(). When writable.write(chunk) returns false, the internal buffer has reached highWaterMark and you must stop writing until the drain event fires. On the read side, switching between flowing and paused mode (via a data listener, pause(), resume() or readable) controls how fast data is pulled. Honouring these signals is what keeps memory bounded when a fast producer feeds a slow consumer.
Tips and examples
- Prefer
stream.pipeline(src, ...transforms, dest, cb)over manualpipe()chains — it forwards errors and destroys every stream on failure, so you do not leak file descriptors. - The ordering on a clean Readable finish is
endthenclose; on a Writable it isfinishthenclose. Anerrorshort-circuits straight toclose. readable(notdata) is the lower-level event: it tells you bytes are available, and you callread()yourself, giving precise control over chunk sizes.