I'm using Node.js's net library to set up a basic TCP socket connection:
net.createServer(function (socket) {
    socket.on("data", function (data) {
        console.log("socket to me:", data);
    });
}).listen();
Is there a way to remove or change the socket.on("data") listener, without closing the connection?  I tried the obvious thing:
net.createServer(function (socket) {
    socket.on("data", function (data) {
        console.log("socket to me:", data.toString());
        socket.on("data", function (data) {
            console.log("ouch");
        });
    });
}).listen(10101);
When I connect from the client:
var client = net.connect({host: "localhost", port: 10101});
client.write("boom!");
It prints socket to me: boom!, as expected.  But the next write outputs:
socket to me: boom!
ouch
Is there any way to alter the first listener, or remove it and replace it with a different one?
It turns out that editing the socket's _events object directly lets you swap out listeners, even if they're anonymous.  For example:
net.createServer(function (socket) {
    socket.on("data", function (data) {
        console.log("socket to me:", data.toString());
        socket._events.data = function (data) {
            console.log("ouch");
        };
    });
}).listen(10101);
And then in the client:
var client = net.connect({host: "localhost", port: 10101});
client.write("boom!");
client.write("boom!");
Outputs:
socket to me: boom!
ouch
Just thought I'd share this here, in case it's useful to anyone else!
How about using a conditional inside the listener?
var firstExecution = true;
net.createServer(function (socket) {
    socket.on("data", function (data) {
        if (firstExecution) {
            console.log("socket to me:", data.toString());
            firstExecution = false;
        }
        else {
            console.log("ouch");
        }
    });
}).listen(10101);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With