Handling packets in nodejs for MMORPG Writing a MMORPG server in nodejs, I have to handle packets. These packets have a structure of 

&lt;length&gt; &lt;id&gt; &lt;data&gt;


So what I did was use a node package called packet

And first get the packet id:

client.on('data', function(data) {
  parser.extract("l16 =&gt; length, l16 =&gt; id", function (packet) {
    if (packet.id === 300) {

    }
    if (packet.id === 301) {

    }
    if (packet.id === 302) {

    }
    if (packet.id === 303) {

    }
  });

  // parse the packet id to handle it accordingly
  parser.parse(data);
});


There are packet Id's upto 1000+ which would make my if statements very long. But each packet id contains different data and different ways to handle it.

For example packet 300 which is the handshake packet. It sends the client version to the server and the servers checks it and returns if it is correct or not, if not then client will error wrong version.

  if (packet.id === 300) {
    console.log('[recieved] packet:handshake');

    parser.extract("handshake", function (packet) {
      if (packet.gameClientVer === config.gameClientVer) {
        // do stuff
      } else {
        // do stuff 
      }
    });

    // parse structure for packet 300
    parser.parse(data);
  }
});


the handshake packet is defined as:

serializer.packet("handshake", "l16 =&gt; length, l16 =&gt; id, l16 =&gt; gameClientVer, l16 =&gt; gameUpdateVer, l16 =&gt; gameDateVer");


My question is, how can I improve this?
You should compartmentalize your "handlers" for each of the packets.  Each handler should contain a canHandle method that determines whether it can process the packet and a process method that does the work.  Example:

var packet300Handler = {
    canHandle: function(packet) {
        return packet.id === 300;
    },
    process: function(packet) {
        // Do work here.
    }
};

var handlers = [packet300Handler, packet301Handler, packet302Handler];

client.on('data', function(data) {
    parser.extract('DATA', function(packet) {
        for (var i = 0; i &lt; handlers.length; i++) {
            var handler = handlers[i];

            if (handler.canHandle(packet)) {
                handler.process(packet);
                break; // Leave loop now that something has handled the packet.
            }
        }
    });
});