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