Skip to content

Commit

Permalink
Merge pull request #1 from tmpvar/cleanup-write
Browse files Browse the repository at this point in the history
reduction of JSONStream#write
  • Loading branch information
mmalecki committed Oct 11, 2012
2 parents 13fbde2 + a1fd0ee commit 9021216
Showing 1 changed file with 8 additions and 17 deletions.
25 changes: 8 additions & 17 deletions lib/json-stream.js
Expand Up @@ -17,29 +17,20 @@ var JSONStream = module.exports.JSONStream = function () {
util.inherits(JSONStream, Stream);

JSONStream.prototype.write = function (data) {
var start = 0, stop = 0, chunk, parsed;

data = data.toString('utf8');
data = this._buffer + data.toString('utf8');

if (this._buffer) {
data = this._buffer + data;
}
var lines = data.split('\n'),
that = this;

while ((stop = data.indexOf('\n', start + 1)) !== -1) {
chunk = data.substr(start, stop - start);
parsed = false;
this._buffer = lines.pop();

lines.forEach(function(line) {
try {
chunk = JSON.parse(chunk);
parsed = true;
that.emit('data', JSON.parse(line));
}
catch (_) { }

if (parsed) {
this.emit('data', chunk);
}
start = stop + 1;
}
this._buffer = data.substr(start);
});

return !this.paused;
};
Expand Down

0 comments on commit 9021216

Please sign in to comment.