A quick overview of the node.js streams interface with basic examples.
This is based on @brycebaril’s presentation, Node.js Streams2 Demystified
Streams are a first-class construct in Node.js for handling data.
Think of them as as lazy evaluation applied to data.
There are essentially three major concepts:
Benefits in using streams:
Five classes of streams:
Readable
- sourcesWritable
- sinksDuplex
- both source and sinkTransform
- in-flight stream operationsPassthrough
- stream spyBelow is a quick overview of Readable, Writable, and Transform streams.
See also:
Use a Readable stream when supplying data as a stream.
Think: spigot/faucet.
Subclass stream.Readable.
Implement a _read(size)
method.
_read(size)
size
is in bytes, but can be ignored (especially for objectMode streams)_read(size)
must call this.push(chunk) to send a chunk to the consumerhighWaterMark
number: maximum number of bytes to store in the internal
buffer before ceasing to read (default: 16kb)
encoding
string: if set, buffers will be decoded to strings instead of
passing buffers (default: null
)
objectmode
boolean: instead of using buffers/strings, use javascript objects
(default: false
)
readable.pipe(target)
readable.read(size)
readable.on("data", ... )
Use a Writable stream when collecting data from a stream.
Think: drain/collect.
Subclass stream.Writable.
Implement a _write(chunk, encoding, callback)
method.
_write(chunk, encoding, callback)
chunk
is the content to writecallback()
when you’re done with this chunkhighWaterMark
number: maximum number of bytes to store in the internal
buffer before ceasing to read (default: 16kb)
decodeStrings
boolean: whether to decode strings to Buffers before passing
them to _write()
(default: true)
source.pipe(sink)
writable.write(chunk [,encoding] [,callback])
Use a Transform stream when you want to operate on a stream in transit. This is a special kind of Duplex stream where the input and output stream are the same stream.
Think: filter/map.
_transform(chunk, encoding, callback)
method._flush(callback)
method._transform(chunk, encoding, callback)
Call this.push(something)
to forward it to the next consumer.
You don’t have to push anything, this will skip a chunk.
You must call callback
one time per _transform
call.
_flush(callback)
When the stream ends, this is your chance to do any cleanup or last-minute this.push()
calls to clear any buffers or work. Call callback()
when done.
Superset of Readable and Writable options.
source.pipe(transform).pipe(drain)
transform.on("data", ... )
objectMode
)