views:

67

answers:

0

I'm implementing a server in node.js for a protocol that has unterminated packets. i.e:

_________________________________________________________________________
| packet type | string length 1 | string 1 | string length 2 | string 2 |

So I don't know the length of the packet until it has been fully parsed.

This causes problems, because sometimes a packet comes distributed across multiple read()s. I need some system of promises, continuations and buffering that will let me write code something like:

function parsePacket(stream) {
  var id = stream.readInt();
  var str1 = stream.readString();
  var str2 = stream.readString();
  stream.writePacket([int(3), 'response']);
}

The idea would be that as soon as parsePacket() ran out of data, it would suspend execution until more data was available.

Does such a library exist? Or do I have to write it myself?