NodeJS net.socket Pipe by condition/filter

511 views Asked by At

I'm new to NodeJS. The existing net.socket pipe need to filter by condition to not to connect to "con2", my existing code as follow.

I found Transform and PipeLine methods and, so far I tried, the sample code not working for my scenario yet.

The condition is in "con1" read stream data have some keyword. e.g. "Output" Then, not to connect or transform data as empty to "con2". So that, "con2" not to process.

Start.js

import Proxy from "./Proxy.js";

const proxy = Proxy();
  proxy.listen('4000');

Proxy.js

import net from "net";

export default () =>
    net.createServer((con1) => {
        const con2 = net.connect(
          '1234',
          '127.0.0.1'
        );
        
        con1.pipe(con2).pipe(con1);
    
        con2.on("data", async (data) => {
          try {
                console.log("sent from con2:", data);
               }
          }
        }
        con1.on("data", async (data) => {
          try {
                console.log("sent from con1:", data);
               }
          }
        }

Please help advise. Thanks a lot in advance.

1

There are 1 answers

13
Marc On BEST ANSWER

I have put something together:

const net = require("net");

const { Transform, pipeline } = require("stream");


const spy = (client) => {
    return new Transform({
        transform(chunk, encoding, cb) {
            if (chunk.toString("utf-8").includes("output")) {

                cb(new Error("ABORTED!"));

            } else {

                cb(null, chunk);

            }
        }
    });
};


let server = net.createServer((socket) => {

    const client = net.connect('1234', '127.0.0.1');

    pipeline(socket, spy(client), client, (err) => {
        console.log("pipeline closed", err);
    });

});

server.listen(1235, "127.0.0.1", () => {
    console.log("Go and send something to the tcp socket, tcp://127.0.0.1:1235")
});

Start a simple netcat server to see what we send there:

while true; do nc -l -p 1234; done;

When we now connect with another netcat, we can send stuff over the proxy to the other netcat instance:

nc 127.0.0.1 1235

When we now send the "output" keyword, the connection gets aborted/terminated.

The spy functions simple inspects the chunk that pass through the transform stream in the pipeline and checks for the string "output", if its found, the pipeline is closed and both client sockets/connections are terminated.