stream `.pipe` does not forward data

Viewed 22

I try to implement a simple "dynamic pipeing" in node.js Whenever data comes from one stream (uplink) a network socket is created and the data should be piped into this socket.

This happens asynchronous and the destination stream is not available when data comes in from the uplink.

The problem is, i dont receive any data in the network socket stream.

To demonstrate the issue, i put a minimal reproducible example together:

const { PassThrough, Readable } = require("stream");


// fake network socket
const socket = new PassThrough();

socket.on("data", (chunk) => {
    console.log("Write to network socket", String(chunk));
});


// fake backend uplink
const uplink = new Readable({
    read(size) {
    }
});

uplink.on("readable", () => {

    console.log("Received data from backend");

    uplink.pipe(socket);

});

setTimeout(() => {
    console.log("Write to upstream");
    uplink.push(`[${Date.now()}] Hello network socket`);
}, 3000);

socket = network socket
uplink = Websocket connection to backend.

The PassThrough stream does not receive any data/emits the data event.

I tried various combinations with .pause() and .cork() and dont understand why the data does not reach its destination.

EDIT: Found a possible solution/workaround, but it seems hacky too me. I read the chunk after the readable emit was emitted and write it after piping both stream to the socket stream.

uplink.once("readable", () => {

    console.log("Received data from backend");

    let chunk = uplink.read();

    uplink.pipe(socket);
    socket.write(chunk);

});

Are there any better approaches?

0 Answers
Related