我想为节点js双工流写一个例子,这样对于两个双工流A和B
如果 A 写了一些东西,它应该被流 B 读取,反之亦然
我是这样写的:
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!');`
现在即使我已经通过管道传输了两个流,也没有得到所需的输出:
A writes: Hello B!
B reads: Hello B!
B writes: Hello A!
A reads: Hello A!