-
Notifications
You must be signed in to change notification settings - Fork 2
/
parser.js
47 lines (40 loc) · 1.22 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
// code imported from jdub/node-twitter
// glorious streaming json parser, built specifically for the twitter streaming api
// assumptions:
// 1) ninjas are mammals
// 2) tweets come in chunks of text, surrounded by {}'s, separated by line breaks
// 3) only one tweet per chunk
//
// p = new parser.instance()
// p.addListener('object', function...)
// p.receive(data)
// p.receive(data)
// ...
var EventEmitter = require('events').EventEmitter;
var Parser = module.exports = function Parser() {
// Make sure we call our parents constructor
EventEmitter.call(this);
this.buffer = '';
return this;
};
// The parser emits events!
Parser.prototype = Object.create(EventEmitter.prototype);
Parser.END = '\r\n';
Parser.END_LENGTH = 2;
Parser.prototype.receive = function receive(buffer) {
this.buffer += buffer.toString('utf8');
var index, json;
// We have END?
while ((index = this.buffer.indexOf(Parser.END)) > -1) {
json = this.buffer.slice(0, index);
this.buffer = this.buffer.slice(index + Parser.END_LENGTH);
if (json.length > 0) {
try {
json = JSON.parse(json);
this.emit('data', json);
} catch (error) {
this.emit('error', error);
}
}
}
};