Search code examples
javascriptnode.jswebsocket

Unregister all event in WebSocket


How can stop listening to all events in websocket.

const WebSocketClient = require('ws');
const ws = new WebSocketClient('wss://example.com');
ws.on('message', doFunction());

function doFunction() {
  if (condition) {
    //do some stuff
    //stop listening to event without closing the websocket connection
  }
}

ws.close() or ws.terminate() will close the connection, I don't want to close the connection.


Solution

  • Since your WebSocketClient extends EventEmitter, you can surely call ws.removeAllListeners().

    EventEmitter.removeAllListeners docs and ws#WebSocket docs should help anyhow.