【问题标题】:pipe issue with Node js Duplex Stream exampleNode js双工流示例的管道问题
【发布时间】:2018-01-29 18:33:11
【问题描述】:

我想写一个node 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!

【问题讨论】:

    标签: pipe duplex nodejs-stream


    【解决方案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!');
    

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

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

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

    【讨论】:

    • 但是,如果我们需要操作数据,就使用转换流,对吧?我不需要转换数据,只需要传递 - 任何由 A 写入 B 的内容,反之亦然
    • 技术上是的,输出取决于输入。你试过我的例子吗?如果这不是您想要的,您可以查看 NodeJS 示例 (nodejs.org/api/stream.html#stream_an_example_duplex_stream),他们在自定义双工流的构造函数中显式声明源
    猜你喜欢
    • 1970-01-01
    • 2016-06-10
    • 2022-01-09
    • 1970-01-01
    • 2014-07-11
    • 2021-09-21
    • 2018-10-07
    • 1970-01-01
    • 2011-08-29
    相关资源
    最近更新 更多