Node js Duplex Stream示例的管道问题

时间:2018-01-29 18:33:12

标签: pipe duplex nodejs-stream

我想为节点js双工流写一个例子 对于两个双工流A和B

如果A写的东西应该由流B读取,反之亦然

我是用这种方式写的:

LC0:
    .ascii "HERE\12\0"
    .text
    .globl  __Z12connect_FUNCjPK8sockaddri@12
    .def    __Z12connect_FUNCjPK8sockaddri@12;  .scl    2;  .type   32; .endef
__Z12connect_FUNCjPK8sockaddri@12:
    pushl   %ebp
    movl    %esp, %ebp
    pushl   %ebx
    orl $-1, %ebx
    subl    $20, %esp
    movl    _jmpOffset, %eax
    testl   %eax, %eax
    je  L8
    movl    %eax, 4(%esp)
    movl    _connect_ORI, %eax
    movl    %eax, (%esp)
    call    __Z11RemovePatchPhS_
    movl    16(%ebp), %eax
    movl    $0, _jmpOffset
    movl    %eax, 8(%esp)
    movl    12(%ebp), %eax
    movl    %eax, 4(%esp)
    movl    8(%ebp), %eax
    movl    %eax, (%esp)
    call    *_connect_ORI
    movl    %eax, %ebx
    movl    _connect_ORI, %eax
    subl    $12, %esp
    movl    $__Z12connect_FUNCjPK8sockaddri@12, 4(%esp)
    movl    %eax, (%esp)
    call    __Z5PatchPhS_
    movl    %eax, _jmpOffset
L8:
    movl    $LC0, (%esp)
    call    __Z6printfPKcz
    movl    %ebx, %eax
    movl    -4(%ebp), %ebx
    leave
    ret $12
    .section .rdata,"dr"

现在即使我已经管道输出两个流,但没有获得所需的输出:

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

1 个答案:

答案 0 :(得分: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!');

您要做的是所谓的变换流。请记住:双工流对外部源进行读取和写入。变换流由你自己控制。

P.S。你会得到某种循环执行它,因为一个管道是多余的

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