avieth/eventsource-node — pull request #2 by avieth (2013-11-12 19:18:54+00:00)
Title: Newlines stripped from head of buffer

In my application, eventsource is used with CouchDB's _changes stream.
CouchDB sends a heartbeat message, which is just a newline. This is appended
to the buffer string (buf) and if the buffer string is empty, then the first
regexp /(.|\r\n|\n|\r)*(\n\n|\r\r|\r\n\r\n)/ will not match it, and messages
will be falsy; no action is taken, and buf is '\n'.

Suppose now that CouchDB responds with some real data, rather than a heartbeat.
We add this real data to the buffer, and the regexp returns a match! However,
that match is prefixed with a newline, so the eventstream parser fails and the
data is lost.

This bug was rather elusive, because if another heartbeat would come,
then we'd have buf == '\n\n' and this would match the first regexp! The
buffer is reset, and the next message is processed normally (assuming it
comes before the next heartbeat).