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!