Skip to content

Instantly share code, notes, and snippets.

@spolu
Created November 24, 2011 12:37
Show Gist options
  • Save spolu/1391264 to your computer and use it in GitHub Desktop.
Save spolu/1391264 to your computer and use it in GitHub Desktop.
Dynamic Parser for \r\n separated JSON objects
var buf = require('buffer');
/**
* Dynamic Parser Object borrowed to twitter-node
*/
var Parser = function Parser() {
events.EventEmitter.call(this);
this.buffer = '';
return this;
};
// The parser emits events!
Parser.prototype = Object.create(events.EventEmitter.prototype);
Parser.END = '\r\n';
Parser.END_LENGTH = 2;
Parser.prototype.receive = function receive(buffer) {
this.buffer += buffer.toString('utf8');
var index, json;
// We have END?
while ((index = this.buffer.indexOf(Parser.END)) > -1) {
json = this.buffer.slice(0, index);
this.buffer = this.buffer.slice(index + Parser.END_LENGTH);
if (json.length > 0) {
try {
json = JSON.parse(json);
this.emit('object', json);
} catch (error) {
this.emit('error', error);
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment