This repository was archived by the owner on Nov 21, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathhiredis.js
57 lines (46 loc) · 1.44 KB
/
hiredis.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
var net = require("net"),
hiredis = require('bindings')('hiredis.node');
var bufStar = new Buffer("*", "ascii");
var bufDollar = new Buffer("$", "ascii");
var bufCrlf = new Buffer("\r\n", "ascii");
exports.Reader = hiredis.Reader;
exports.writeCommand = function() {
var args = arguments,
bufLen = new Buffer(String(args.length), "ascii"),
parts = [bufStar, bufLen, bufCrlf],
size = 3 + bufLen.length;
for (var i = 0; i < args.length; i++) {
var arg = args[i];
if (!Buffer.isBuffer(arg))
arg = new Buffer(String(arg));
bufLen = new Buffer(String(arg.length), "ascii");
parts = parts.concat([
bufDollar, bufLen, bufCrlf,
arg, bufCrlf
]);
size += 5 + bufLen.length + arg.length;
}
return Buffer.concat(parts, size);
}
exports.createConnection = function(port, host) {
var s = net.createConnection(port || 6379, host);
var r = new hiredis.Reader();
var _write = s.write;
s.write = function() {
var data = exports.writeCommand.apply(this, arguments);
return _write.call(s, data);
}
s.on("data", function(data) {
var reply;
r.feed(data);
try {
while((reply = r.get()) !== undefined)
s.emit("reply", reply);
} catch(err) {
r = null;
s.emit("error", err);
s.destroy();
}
});
return s;
}