2015-04-30 04:00:04 +00:00
|
|
|
define(function(require, exports, module) {
|
|
|
|
|
|
|
|
var EventEmitter = require("events").EventEmitter;
|
|
|
|
|
|
|
|
module.exports = function(stream) {
|
2015-04-30 22:30:29 +00:00
|
|
|
var emit = this.emit.bind(this);
|
2015-04-30 04:00:04 +00:00
|
|
|
|
|
|
|
var buffer = "";
|
|
|
|
stream.on("data", function(chunk) {
|
|
|
|
buffer += chunk;
|
|
|
|
|
|
|
|
var parts = buffer.split("\n");
|
|
|
|
while (parts.length) {
|
|
|
|
try {
|
2015-04-30 22:30:29 +00:00
|
|
|
var message = JSON.parse(parts[0]);
|
|
|
|
emit("data", message);
|
|
|
|
parts.shift();
|
2015-04-30 04:00:04 +00:00
|
|
|
}
|
|
|
|
catch (e) {
|
|
|
|
if (parts.length !== 1) {
|
|
|
|
emit("error", e);
|
2015-04-30 22:30:29 +00:00
|
|
|
parts.shift();
|
2015-04-30 04:00:04 +00:00
|
|
|
}
|
|
|
|
else {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
buffer = parts.join("\n");
|
|
|
|
});
|
|
|
|
|
|
|
|
stream.on("error", function(err){
|
2015-04-30 22:30:29 +00:00
|
|
|
emit("error", err);
|
2015-04-30 04:00:04 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
stream.on("close", function(data){
|
|
|
|
emit("close", data);
|
|
|
|
});
|
|
|
|
|
2015-04-30 22:30:29 +00:00
|
|
|
this.write = function(data) {
|
|
|
|
stream.write(JSON.stringify(data) + "\n");
|
|
|
|
};
|
2015-04-30 04:00:04 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
module.exports.prototype = new EventEmitter();
|
|
|
|
|
|
|
|
});
|