UNPKG

1.06 kBJavaScriptView Raw
1//
2// Parser - for Twitter Streaming API
3//
4var util = require('util')
5 , EventEmitter = require('events').EventEmitter;
6
7var Parser = module.exports = function () {
8 this.message = ''
9
10 EventEmitter.call(this);
11};
12
13util.inherits(Parser, EventEmitter);
14
15Parser.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 try {
36 var msg = JSON.parse(piece)
37 } catch (err) {
38 this.emit('error', new Error('Error parsing twitter reply: `'+piece+'`, error message `'+err+'`'));
39 } finally {
40 if (msg)
41 this.emit('element', msg)
42
43 continue
44 }
45 }
46 offset++;
47 }
48
49 this.message = chunk.slice(start, size);
50};