parser.js (1284B)
1 // 2 // Parser - for Twitter Streaming API 3 // 4 var util = require('util') 5 , EventEmitter = require('events').EventEmitter; 6 7 var Parser = module.exports = function () { 8 this.message = '' 9 10 EventEmitter.call(this); 11 }; 12 13 util.inherits(Parser, EventEmitter); 14 15 Parser.prototype.parse = function (chunk) { 16 this.message += chunk; 17 chunk = this.message; 18 19 var size = chunk.length 20 , start = 0 21 , offset = 0 22 , curr 23 , next; 24 25 while (offset < size) { 26 curr = chunk[offset]; 27 next = chunk[offset + 1]; 28 29 if (curr === '\r' && next === '\n') { 30 var piece = chunk.slice(start, offset); 31 start = offset += 2; 32 33 if (!piece.length) { continue; } //empty object 34 35 if (piece === 'Exceeded connection limit for user') { 36 this.emit('connection-limit-exceeded', 37 new Error('Twitter says: ' + piece + '. Only instantiate one stream per set of credentials.')); 38 continue; 39 } 40 41 try { 42 var msg = JSON.parse(piece) 43 } catch (err) { 44 this.emit('error', new Error('Error parsing twitter reply: `'+piece+'`, error message `'+err+'`')); 45 } finally { 46 if (msg) 47 this.emit('element', msg) 48 49 continue 50 } 51 } 52 offset++; 53 } 54 55 this.message = chunk.slice(start, size); 56 };