Binary stream multiplexer - stream multiple streams of binary data over a single binary stream.
npm install @postalsys/multiplex
- Node.js v22+
const { PassThrough } = require('stream');
const { Multiplex } = require('@postalsys/multiplex');
const multiplex1 = new Multiplex();
const multiplex2 = new Multiplex();
// Listen for incoming streams
multiplex2.on('stream', (meta, stream) => {
// stream is Duplex stream
console.log('STREAM ID', meta.id);
console.log('TARGET HOST', meta.target.host);
console.log('TARGET PORT', meta.target.port);
stream.pipe(process.stdout);
process.stdin.pipe(stream);
});
// Connect multiplexers
multiplex1.pipe(new PassThrough()).pipe(multiplex2);
multiplex2.pipe(new PassThrough()).pipe(multiplex1);
// Create a new multiplexed stream
const stream = multiplex1.createStream({ target: { host: '1.2.3.4', port: 4567 } });
// Write data to the stream
stream.write(Buffer.from('Stream data'));
// Read data from the stream
stream.on('readable', () => {
let chunk;
while ((chunk = stream.read()) !== null) {
console.log(chunk.toString());
}
});
Creates a new Multiplex instance. The Multiplex class extends Transform stream.
Creates a new multiplexed stream with optional metadata.
meta
(Object): Optional metadata to associate with the streamid
(String): Optional stream ID. If not provided, a unique ID will be auto-assigned- Other properties: Any additional metadata you want to pass
- Returns: MultiplexStream instance (Duplex stream)
Emitted when a new stream is received from the remote multiplex.
meta
(Object): Metadata associated with the streamstream
(MultiplexStream): The received duplex stream
Run tests using Node.js built-in test runner:
npm test
MIT