muxdemux
multiplex and demultiplex (mux / demux) streams into an single stream (object mode or not)
Installation
npm i --save muxdemux
Usage
Example: muxdemux substreams
var muxdemux = var mux = var demux = muxmuxmux { if name === 'foo' substream substream else if name === 'bar' substream }
Example: muxdemux substream events
Substream events are encoded and sent down the stream as data packets. Demux streams will decode these data packets and emit the events as if they occurred on downstream substreams themselves. All emitted from a mux.substream().emit(...) will be propagated to downstream substreams.
var muxdemux = var mux = var demux = muxmuxmuxmux { if name === 'foo' // buffers are encoded on json and reparsed as buffers substream
Example: muxdemux object mode streams
For now muxdemux assumes that substreams share the same objectMode as their parents; substreams of objectMode:true mux/demux streams will also be objectMode:true and vice versa.
var muxdemux = var mux = muxdemuxvar demux = muxdemuxmuxmuxmux { if name === 'foo' substream substream else if name === 'bar' substream }
Example: muxdemux substreams end
If all of a mux/demux's substreams end the mux/demux stream will also end. The same is also true for the opposite. If a mux/demux stream ends, it's substreams will be ended.
var muxdemux = var mux = muxdemuxvar demux = muxdemuxmuxdemuxmuxvar foo = muxfoovar bar = muxbar// end substreamsfoobar { // get's called bc all substreams ended (both foo and bar)} { // get's called downstream bc all substreams ended (both foo and bar)}
Example: unexpected muxdemux finish
If a muxdemux finishes before it's substreams it will emit an error to each unfinished substream.
This default behavior can be disabled by passing opts.unexpectedFinishError = false
var muxdemux = var mux = muxdemuxvar foo = muxvar bar = muxfoobarbar // bar ends first, hence no errormux
Example: unexpected muxdemux error
If a muxdemux errors before it's substreams finish it will emit an error to each unfinished substream.
This default behavior can be disabled by passing opts.unexpectedFinishError = false
var muxdemux = var mux = muxdemuxvar foo = muxvar bar = muxfoobarbar // bar ends first, hence no errormux
Example: circular streams
Circular substream data is filtered out of muxdemux streams by default. But if you want to be explicit and prevent non-substream
data from infinitely circulating through your stream use opts.circular
. opts.circular
will filter out non-substream data.
Circular streams are useful if you want substream events to be emitted "upstream" and "downstream".
// server.jsvar muxdemux = var websocket = /* ... */var mux = websocketvar fooSubstream = muxfooSubstream // client.jsvar muxdemux = var websocket = /* ... */var mux = websocketvar fooSubstream = demuxfooSubstreamfooSubstream
License
MIT