-
Notifications
You must be signed in to change notification settings - Fork 17
/
carrier.js
64 lines (49 loc) · 1.38 KB
/
carrier.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
57
58
59
60
61
62
63
64
var util = require('util'),
events = require('events'),
dgram = require('dgram');
function Carrier(reader, listener, encoding, separator) {
var self = this;
var eventName = (reader.constructor === dgram.Socket) ? 'message' : 'data';
var buffer = '';
self.reader = reader;
encoding = encoding || 'utf-8';
separator = separator || /\r?\n/;
if (listener) {
self.addListener('line', listener);
}
if (typeof reader.setEncoding === 'function') {
reader.setEncoding(encoding);
}
var defferredLineEmit = function(line) {
process.nextTick(function() {
self.emit('line', line);
});
};
var onData = function carrierOnData(data) {
if (data instanceof Buffer) {
data = data.toString(encoding);
}
data = buffer + data;
var lines = data.split(separator);
var length = lines.length - 1;
buffer = lines[length] || '';
for (var i = 0; i < length; i++) {
defferredLineEmit(lines[i]);
}
};
var onEnd = function onEnd() {
if (buffer) {
defferredLineEmit(buffer);
buffer = '';
}
process.nextTick(function() {
self.emit('end');
});
};
reader.on(eventName, onData);
reader.on('end', onEnd);
}
util.inherits(Carrier, events.EventEmitter);
exports.carry = function(reader, listener, encoding, separator) {
return new Carrier(reader, listener, encoding, separator);
}