1

I would like to write an example for node js duplex streams, such that for two duplex streams A and B

If A writes something it should be read by stream B and vice versa

I have written it in this way:

const Duplex = require('stream').Duplex;

class MyDuplex extends Duplex {
    constructor(name, options) {
        super(options);
        this.name = name;
    }

    _read(size) {}

    _write(chunk, encoding, callback) {
        console.log(this.name + ' writes: ' + chunk + '\n');
        callback();
    }
}

let aStream = new MyDuplex('A');
let bStream = new MyDuplex('B');


aStream.pipe(bStream).pipe(aStream);

aStream.on('data', (chunk) => {
    console.log('A read: ' + chunk + '\n');
})

aStream.write('Hello B!');

bStream.on('data', (chunk) => {
    console.log('B read: ' + chunk + '\n');
})
bStream.write('Hello A!');`

Now even though I have piped the two streams, not getting the desired Output:

A writes: Hello B!
B reads: Hello B!
B writes: Hello A! 
A reads: Hello A!
vmt
  • 41
  • 1
  • 4

1 Answers1

1
const Transform = require('stream').Transform;

class MyDuplex extends Transform {
    constructor(name, options) {
        super(options);
        this.name = name;
    }


    _transform(chunk, encoding, callback) {
        this.push(chunk);
        console.log(this.name + ' writes: ' + chunk + '\n');
        callback();
    }
}

let aStream = new MyDuplex('A');
let bStream = new MyDuplex('B');


aStream.pipe(bStream).pipe(aStream);

aStream.on('end', (chunk) => {
    console.log('A read: ' + chunk + '\n');
})

aStream.write('Hello B some bytes more!');
aStream.resume();

bStream.on('end', (chunk) => {
    console.log('B read: ' + chunk + '\n');
});

bStream.write('Hello A!');

What you want to do is a so called Transform stream. Remember: A Duplex Stream reads and write from and respectievly to external Sources. Transform streams are controlled by yourself.

p.s. youll get some kind of loop executing this because one pipe is redundant

sources: https://nodejs.org/api/stream.html#stream_implementing_a_transform_stream

  • But, transform streams are used if we need to manipulate the data, Right? I don't need to transform the data, just need to pass - whatever written by A to B & vice versa – vmt Jan 30 '18 at 04:43
  • technically yes, the output depends on the input. Did you tried my example though? If this is not what you want you could take a look at the NodeJS example (https://nodejs.org/api/stream.html#stream_an_example_duplex_stream) they declare a source explicitly in the constructor of their custom duplex-stream –  Jan 30 '18 at 07:36