1 |
|
2 |
|
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; }
|
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 | };
|