1

我想为节点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!
4

1 回答 1

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!');

您想要做的是所谓的转换流。请记住:双工流分别从外部源读取和写入。转换流由您自己控制。

ps 你会得到某种循环来执行这个,因为一个管道是多余的

来源: https ://nodejs.org/api/stream.html#stream_implementing_a_transform_stream

于 2018-01-29T19:16:20.783 回答