Skip to content

postalsys/multiplex

Repository files navigation

@postalsys/multiplex

Binary stream multiplexer - stream multiple streams of binary data over a single binary stream.

Installation

npm install @postalsys/multiplex

Requirements

  • Node.js v22+

Usage

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());
    }
});

API

new Multiplex(options)

Creates a new Multiplex instance. The Multiplex class extends Transform stream.

multiplex.createStream(meta)

Creates a new multiplexed stream with optional metadata.

  • meta (Object): Optional metadata to associate with the stream
    • id (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)

Event: 'stream'

Emitted when a new stream is received from the remote multiplex.

  • meta (Object): Metadata associated with the stream
  • stream (MultiplexStream): The received duplex stream

Testing

Run tests using Node.js built-in test runner:

npm test

License

MIT

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published