Mux Demux Stream
Multiplex and demultiplex up to eight binary/text streams with a single multiplexer or demultiplexer. Each chunk of data is prepended with a five bytes header, including channel id and payload length.
|1 byte (Channel ID)||4 bytes (Payload length)||Original payload of variable length|
npm install mux-demux-stream
The module can be used both with a "simplex" syntax and with a "duplex" syntax that offers some syntactic sugar over the simplex variant.
The simplex syntax is used for multiplexing several readable streams into a single writable stream, or demultiplexing several writable streams into a single readable stream.
The duplex syntax is more compact when for example implementing a protocol like JSON RPC 2.0 in a peer-to-peer fashion, where each RPC node consist of a server and a client that share a common bidirectional channel such as WebSockets. (See json-rpc-server-stream and json-rpc-client-stream for a more comprehensive discussion about using JSON RPC 2.0 in a peer-to-peer fashion.)
Require module and specific functions.
var mux = mux;var demux = demux;
Combine multiple streams to allow transmission over a single stream.
var sourceA = ;var sourceB = ;var destination = ;;
Reconstruct the original streams from the data received from a shared stream.
var source = ;var destinationA = ;var destinationB = ;;
Require module. (Note that this is not the same
mux function as in the example
var mux = ;
mux(channel1[, ...]).pipe(sharedChannel).demux(channel1[, ...])
Internally the duplex variant uses "chaining" and closures to form a natural stream syntax when several duplex streams are multiplexed into and from a shared channel stream.
The following simplex syntax:
is equivalent to the following duplex syntax:
Run unit tests: