Skip to content

Instantly share code, notes, and snippets.

@Sannis
Forked from joekim/json-protocol.js
Created December 7, 2011 09:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sannis/1442147 to your computer and use it in GitHub Desktop.
Save Sannis/1442147 to your computer and use it in GitHub Desktop.
A simple carriage-return, line-feed delimited JSON protocol.
/*
A simple carriage-return, line-feed delimited JSON protocol.
Receiving Usage:
protocol = require('./json-protocol');
// parsing data
parser = protocol.StreamParser();
parser.on('message', function (msg) {
// handle message
});
socket.on('data', function (data) {
parser.read(data);
});
Sending Usage:
protocol = require('./frame-protocol');
socket.write(protocol.serialize({"hello": "world"}));
Based on code from:
https://gist.github.com/880514
https://github.com/joyent/node/blob/f44d0b90442d9a1dc7457924f827722fc3a7c440/lib/child_process.js#L71-141
*/
var util = require('util');
var events = require('events');
var CR = '\r'.charCodeAt(0);
var LF = '\n'.charCodeAt(0);
var DELIMITER = '\r\n';
var ENCODING = 'ascii';
var ERROR = 'error';
var MESSAGE = 'message';
function StreamParser(){
if (!(this instanceof StreamParser)){
return new StreamParser();
}
events.EventEmitter.call(this);
this.buffer = '';
}
util.inherits(StreamParser, events.EventEmitter);
function read(data){
this.buffer += data.toString(ENCODING);
var buffer = this.buffer;
var start = 0, len = buffer.length;
for(i = 0; i + 1 < len; ++i){
var charCode = buffer.charCodeAt(i);
var nextCharCode = buffer.charCodeAt(i + 1);
if (charCode === CR && nextCharCode === LF){
var json = buffer.slice(start, i);
try {
var message = JSON.parse(json);
this.emit(MESSAGE, message);
}
catch(err){
this.emit(ERROR, err);
}
start = i + 2;
++i;
}
}
if (i < len){
this.buffer = buffer.slice(start);
}
else {
this.buffer = '';
}
}
function serialize(message){
return JSON.stringify(message) + DELIMITER;
}
StreamParser.prototype.read = read;
StreamParser.prototype.serialize = serialize;
exports.StreamParser = StreamParser;
exports.serialize = serialize;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment