1
0
mirror of https://github.com/redis/node-redis.git synced 2025-08-04 15:02:09 +03:00

Small style changes

This commit is contained in:
Ruben Bridgewater
2015-10-04 21:44:52 +02:00
parent 2fc54ece57
commit 7922d4eb85
28 changed files with 386 additions and 390 deletions

View File

@@ -196,13 +196,13 @@ once the connection has been established. Setting `enable_offline_queue` to
with an error, or an error will be emitted if no callback is specified. with an error, or an error will be emitted if no callback is specified.
* `retry_max_delay`: *null*; By default every time the client tries to connect and fails the reconnection delay almost doubles. * `retry_max_delay`: *null*; By default every time the client tries to connect and fails the reconnection delay almost doubles.
This delay normally grows infinitely, but setting `retry_max_delay` limits it to the maximum value, provided in milliseconds. This delay normally grows infinitely, but setting `retry_max_delay` limits it to the maximum value, provided in milliseconds.
* `connect_timeout` *86400000*; Setting `connect_timeout` limits total time for client to reconnect. * `connect_timeout`: *86400000*; Setting `connect_timeout` limits total time for client to reconnect.
The value is provided in milliseconds and is counted once the disconnect occurred. The last retry is going to happen exactly at the timeout time. The value is provided in milliseconds and is counted once the disconnect occurred. The last retry is going to happen exactly at the timeout time.
That way the default is to try reconnecting until 24h passed. That way the default is to try reconnecting until 24h passed.
* `max_attempts` *0*; By default client will try reconnecting until connected. Setting `max_attempts` * `max_attempts`: *0*; By default client will try reconnecting until connected. Setting `max_attempts`
limits total amount of connection tries. Setting this to 1 will prevent any reconnect tries. limits total amount of connection tries. Setting this to 1 will prevent any reconnect tries.
* `auth_pass` *null*; If set, client will run redis auth command on connect. * `auth_pass`: *null*; If set, client will run redis auth command on connect.
* `family` *IPv4*; You can force using IPv6 if you set the family to 'IPv6'. See Node.js [net](https://nodejs.org/api/net.html) or [dns](https://nodejs.org/api/dns.html) modules how to use the family type. * `family`: *IPv4*; You can force using IPv6 if you set the family to 'IPv6'. See Node.js [net](https://nodejs.org/api/net.html) or [dns](https://nodejs.org/api/dns.html) modules how to use the family type.
* `disable_resubscribing`: *false*; If set to `true`, a client won't resubscribe after disconnecting * `disable_resubscribing`: *false*; If set to `true`, a client won't resubscribe after disconnecting
```js ```js

View File

@@ -7,56 +7,56 @@ for (i = 99 ; i >= 0 ; i--) {
source[i] = 120; source[i] = 120;
} }
var str = "This is a nice String.", var str = 'This is a nice String.',
buf = new Buffer("This is a lovely Buffer."); buf = new Buffer('This is a lovely Buffer.');
var start = new Date(); var start = new Date();
for (i = count * 100; i > 0 ; i--) { for (i = count * 100; i > 0 ; i--) {
if (Buffer.isBuffer(str)) {} if (Buffer.isBuffer(str)) {}
} }
var end = new Date(); var end = new Date();
console.log("Buffer.isBuffer(str) " + (end - start) + " ms"); console.log('Buffer.isBuffer(str) ' + (end - start) + ' ms');
var start = new Date(); var start = new Date();
for (i = count * 100; i > 0 ; i--) { for (i = count * 100; i > 0 ; i--) {
if (Buffer.isBuffer(buf)) {} if (Buffer.isBuffer(buf)) {}
} }
var end = new Date(); var end = new Date();
console.log("Buffer.isBuffer(buf) " + (end - start) + " ms"); console.log('Buffer.isBuffer(buf) ' + (end - start) + ' ms');
var start = new Date(); var start = new Date();
for (i = count * 100; i > 0 ; i--) { for (i = count * 100; i > 0 ; i--) {
if (str instanceof Buffer) {} if (str instanceof Buffer) {}
} }
var end = new Date(); var end = new Date();
console.log("str instanceof Buffer " + (end - start) + " ms"); console.log('str instanceof Buffer ' + (end - start) + ' ms');
var start = new Date(); var start = new Date();
for (i = count * 100; i > 0 ; i--) { for (i = count * 100; i > 0 ; i--) {
if (buf instanceof Buffer) {} if (buf instanceof Buffer) {}
} }
var end = new Date(); var end = new Date();
console.log("buf instanceof Buffer " + (end - start) + " ms"); console.log('buf instanceof Buffer ' + (end - start) + ' ms');
for (i = bytes ; i > 0 ; i --) { for (i = bytes ; i > 0 ; i --) {
var start = new Date(); var start = new Date();
for (j = count ; j > 0; j--) { for (j = count ; j > 0; j--) {
tmp = source.toString("ascii", 0, bytes); tmp = source.toString('ascii', 0, bytes);
} }
var end = new Date(); var end = new Date();
console.log("toString() " + i + " bytes " + (end - start) + " ms"); console.log('toString() ' + i + ' bytes ' + (end - start) + ' ms');
} }
for (i = bytes ; i > 0 ; i --) { for (i = bytes ; i > 0 ; i --) {
var start = new Date(); var start = new Date();
for (j = count ; j > 0; j--) { for (j = count ; j > 0; j--) {
tmp = ""; tmp = '';
for (k = 0; k <= i ; k++) { for (k = 0; k <= i ; k++) {
tmp += String.fromCharCode(source[k]); tmp += String.fromCharCode(source[k]);
} }
} }
var end = new Date(); var end = new Date();
console.log("manual string " + i + " bytes " + (end - start) + " ms"); console.log('manual string ' + i + ' bytes ' + (end - start) + ' ms');
} }
for (i = bytes ; i > 0 ; i--) { for (i = bytes ; i > 0 ; i--) {
@@ -67,7 +67,7 @@ for (i = bytes ; i > 0 ; i--) {
} }
} }
var end = new Date(); var end = new Date();
console.log("Manual copy " + i + " bytes " + (end - start) + " ms"); console.log('Manual copy ' + i + ' bytes ' + (end - start) + ' ms');
} }
for (i = bytes ; i > 0 ; i--) { for (i = bytes ; i > 0 ; i--) {
@@ -78,7 +78,7 @@ for (i = bytes ; i > 0 ; i--) {
} }
} }
var end = new Date(); var end = new Date();
console.log("Direct assignment " + i + " bytes " + (end - start) + " ms"); console.log('Direct assignment ' + i + ' bytes ' + (end - start) + ' ms');
} }
for (i = bytes ; i > 0 ; i--) { for (i = bytes ; i > 0 ; i--) {
@@ -87,5 +87,5 @@ for (i = bytes ; i > 0 ; i--) {
source.copy(dest, 0, 0, i); source.copy(dest, 0, 0, i);
} }
var end = new Date(); var end = new Date();
console.log("Buffer.copy() " + i + " bytes " + (end - start) + " ms"); console.log('Buffer.copy() ' + i + ' bytes ' + (end - start) + ' ms');
} }

View File

@@ -40,7 +40,7 @@ function parseInt10(s) {
// green if greater than 0, red otherwise // green if greater than 0, red otherwise
function humanize_diff(num, unit) { function humanize_diff(num, unit) {
unit = unit || ""; unit = unit || '';
if (num > 0) { if (num > 0) {
return ('+' + num + unit).green; return ('+' + num + unit).green;
} }

View File

@@ -1,11 +1,11 @@
'use strict'; 'use strict';
var path = require('path'); var path = require('path');
var RedisProcess = require("../test/lib/redis-process"); var RedisProcess = require('../test/lib/redis-process');
var rp; var rp;
var redis = require("../index"); var redis = require('../index');
var totalTime = 0; var totalTime = 0;
var metrics = require("metrics"); var metrics = require('metrics');
var num_clients = parseInt(process.argv[2], 10) || 5; var num_clients = parseInt(process.argv[2], 10) || 5;
var num_requests = 50000; var num_requests = 50000;
var tests = []; var tests = [];
@@ -19,7 +19,7 @@ var small_str, large_str, small_buf, large_buf, very_large_str, very_large_buf;
function lpad(input, len, chr) { function lpad(input, len, chr) {
var str = input.toString(); var str = input.toString();
chr = chr || " "; chr = chr || ' ';
while (str.length < len) { while (str.length < len) {
str = chr + str; str = chr + str;
@@ -30,7 +30,7 @@ function lpad(input, len, chr) {
metrics.Histogram.prototype.print_line = function () { metrics.Histogram.prototype.print_line = function () {
var obj = this.printObj(); var obj = this.printObj();
return lpad(obj.min, 4) + "/" + lpad(obj.max, 4) + "/" + lpad(obj.mean.toFixed(2), 7) + "/" + lpad(obj.p95.toFixed(2), 7); return lpad(obj.min, 4) + '/' + lpad(obj.max, 4) + '/' + lpad(obj.mean.toFixed(2), 7) + '/' + lpad(obj.p95.toFixed(2), 7);
}; };
function Test(args) { function Test(args) {
@@ -66,14 +66,14 @@ Test.prototype.new_client = function (id) {
new_client = redis.createClient(this.client_options); new_client = redis.createClient(this.client_options);
new_client.create_time = Date.now(); new_client.create_time = Date.now();
new_client.on("connect", function () { new_client.on('connect', function () {
self.connect_latency.update(Date.now() - new_client.create_time); self.connect_latency.update(Date.now() - new_client.create_time);
}); });
new_client.on("ready", function () { new_client.on('ready', function () {
if (! versions_logged) { if (! versions_logged) {
console.log("Client count: " + num_clients + ", node version: " + process.versions.node + ", server version: " + console.log('Client count: ' + num_clients + ', node version: ' + process.versions.node + ', server version: ' +
new_client.server_info.redis_version + ", parser: " + new_client.reply_parser.name); new_client.server_info.redis_version + ', parser: ' + new_client.reply_parser.name);
versions_logged = true; versions_logged = true;
} }
self.ready_latency.update(Date.now() - new_client.create_time); self.ready_latency.update(Date.now() - new_client.create_time);
@@ -84,7 +84,7 @@ Test.prototype.new_client = function (id) {
}); });
// If no redis server is running, start one // If no redis server is running, start one
new_client.on("error", function(err) { new_client.on('error', function(err) {
if (err.code === 'CONNECTION_BROKEN') { if (err.code === 'CONNECTION_BROKEN') {
throw err; throw err;
} }
@@ -105,7 +105,7 @@ Test.prototype.new_client = function (id) {
}; };
Test.prototype.on_clients_ready = function () { Test.prototype.on_clients_ready = function () {
process.stdout.write(lpad(this.args.descr, 13) + ", " + lpad(this.args.pipeline, 5) + "/" + this.clients_ready + " "); process.stdout.write(lpad(this.args.descr, 13) + ', ' + lpad(this.args.pipeline, 5) + '/' + this.clients_ready + ' ');
this.test_start = Date.now(); this.test_start = Date.now();
this.fill_pipeline(); this.fill_pipeline();
@@ -159,64 +159,64 @@ Test.prototype.print_stats = function () {
var duration = Date.now() - this.test_start; var duration = Date.now() - this.test_start;
totalTime += duration; totalTime += duration;
console.log("min/max/avg/p95: " + this.command_latency.print_line() + " " + lpad(duration, 6) + "ms total, " + console.log('min/max/avg/p95: ' + this.command_latency.print_line() + ' ' + lpad(duration, 6) + 'ms total, ' +
lpad((this.num_requests / (duration / 1000)).toFixed(2), 8) + " ops/sec"); lpad((this.num_requests / (duration / 1000)).toFixed(2), 8) + ' ops/sec');
}; };
small_str = "1234"; small_str = '1234';
small_buf = new Buffer(small_str); small_buf = new Buffer(small_str);
large_str = (new Array(4096 + 1).join("-")); large_str = (new Array(4096 + 1).join('-'));
large_buf = new Buffer(large_str); large_buf = new Buffer(large_str);
very_large_str = (new Array((4 * 1024 * 1024) + 1).join("-")); very_large_str = (new Array((4 * 1024 * 1024) + 1).join('-'));
very_large_buf = new Buffer(very_large_str); very_large_buf = new Buffer(very_large_str);
tests.push(new Test({descr: "PING", command: "ping", args: [], pipeline: 1})); tests.push(new Test({descr: 'PING', command: 'ping', args: [], pipeline: 1}));
tests.push(new Test({descr: "PING", command: "ping", args: [], pipeline: 50})); tests.push(new Test({descr: 'PING', command: 'ping', args: [], pipeline: 50}));
tests.push(new Test({descr: "SET 4B str", command: "set", args: ["foo_rand000000000000", small_str], pipeline: 1})); tests.push(new Test({descr: 'SET 4B str', command: 'set', args: ['foo_rand000000000000', small_str], pipeline: 1}));
tests.push(new Test({descr: "SET 4B str", command: "set", args: ["foo_rand000000000000", small_str], pipeline: 50})); tests.push(new Test({descr: 'SET 4B str', command: 'set', args: ['foo_rand000000000000', small_str], pipeline: 50}));
tests.push(new Test({descr: "SET 4B buf", command: "set", args: ["foo_rand000000000000", small_buf], pipeline: 1})); tests.push(new Test({descr: 'SET 4B buf', command: 'set', args: ['foo_rand000000000000', small_buf], pipeline: 1}));
tests.push(new Test({descr: "SET 4B buf", command: "set", args: ["foo_rand000000000000", small_buf], pipeline: 50})); tests.push(new Test({descr: 'SET 4B buf', command: 'set', args: ['foo_rand000000000000', small_buf], pipeline: 50}));
tests.push(new Test({descr: "GET 4B str", command: "get", args: ["foo_rand000000000000"], pipeline: 1})); tests.push(new Test({descr: 'GET 4B str', command: 'get', args: ['foo_rand000000000000'], pipeline: 1}));
tests.push(new Test({descr: "GET 4B str", command: "get", args: ["foo_rand000000000000"], pipeline: 50})); tests.push(new Test({descr: 'GET 4B str', command: 'get', args: ['foo_rand000000000000'], pipeline: 50}));
tests.push(new Test({descr: "GET 4B buf", command: "get", args: ["foo_rand000000000000"], pipeline: 1, client_opts: { return_buffers: true} })); tests.push(new Test({descr: 'GET 4B buf', command: 'get', args: ['foo_rand000000000000'], pipeline: 1, client_opts: { return_buffers: true} }));
tests.push(new Test({descr: "GET 4B buf", command: "get", args: ["foo_rand000000000000"], pipeline: 50, client_opts: { return_buffers: true} })); tests.push(new Test({descr: 'GET 4B buf', command: 'get', args: ['foo_rand000000000000'], pipeline: 50, client_opts: { return_buffers: true} }));
tests.push(new Test({descr: "SET 4KiB str", command: "set", args: ["foo_rand000000000001", large_str], pipeline: 1})); tests.push(new Test({descr: 'SET 4KiB str', command: 'set', args: ['foo_rand000000000001', large_str], pipeline: 1}));
tests.push(new Test({descr: "SET 4KiB str", command: "set", args: ["foo_rand000000000001", large_str], pipeline: 50})); tests.push(new Test({descr: 'SET 4KiB str', command: 'set', args: ['foo_rand000000000001', large_str], pipeline: 50}));
tests.push(new Test({descr: "SET 4KiB buf", command: "set", args: ["foo_rand000000000001", large_buf], pipeline: 1})); tests.push(new Test({descr: 'SET 4KiB buf', command: 'set', args: ['foo_rand000000000001', large_buf], pipeline: 1}));
tests.push(new Test({descr: "SET 4KiB buf", command: "set", args: ["foo_rand000000000001", large_buf], pipeline: 50})); tests.push(new Test({descr: 'SET 4KiB buf', command: 'set', args: ['foo_rand000000000001', large_buf], pipeline: 50}));
tests.push(new Test({descr: "GET 4KiB str", command: "get", args: ["foo_rand000000000001"], pipeline: 1})); tests.push(new Test({descr: 'GET 4KiB str', command: 'get', args: ['foo_rand000000000001'], pipeline: 1}));
tests.push(new Test({descr: "GET 4KiB str", command: "get", args: ["foo_rand000000000001"], pipeline: 50})); tests.push(new Test({descr: 'GET 4KiB str', command: 'get', args: ['foo_rand000000000001'], pipeline: 50}));
tests.push(new Test({descr: "GET 4KiB buf", command: "get", args: ["foo_rand000000000001"], pipeline: 1, client_opts: { return_buffers: true} })); tests.push(new Test({descr: 'GET 4KiB buf', command: 'get', args: ['foo_rand000000000001'], pipeline: 1, client_opts: { return_buffers: true} }));
tests.push(new Test({descr: "GET 4KiB buf", command: "get", args: ["foo_rand000000000001"], pipeline: 50, client_opts: { return_buffers: true} })); tests.push(new Test({descr: 'GET 4KiB buf', command: 'get', args: ['foo_rand000000000001'], pipeline: 50, client_opts: { return_buffers: true} }));
tests.push(new Test({descr: "INCR", command: "incr", args: ["counter_rand000000000000"], pipeline: 1})); tests.push(new Test({descr: 'INCR', command: 'incr', args: ['counter_rand000000000000'], pipeline: 1}));
tests.push(new Test({descr: "INCR", command: "incr", args: ["counter_rand000000000000"], pipeline: 50})); tests.push(new Test({descr: 'INCR', command: 'incr', args: ['counter_rand000000000000'], pipeline: 50}));
tests.push(new Test({descr: "LPUSH", command: "lpush", args: ["mylist", small_str], pipeline: 1})); tests.push(new Test({descr: 'LPUSH', command: 'lpush', args: ['mylist', small_str], pipeline: 1}));
tests.push(new Test({descr: "LPUSH", command: "lpush", args: ["mylist", small_str], pipeline: 50})); tests.push(new Test({descr: 'LPUSH', command: 'lpush', args: ['mylist', small_str], pipeline: 50}));
tests.push(new Test({descr: "LRANGE 10", command: "lrange", args: ["mylist", "0", "9"], pipeline: 1})); tests.push(new Test({descr: 'LRANGE 10', command: 'lrange', args: ['mylist', '0', '9'], pipeline: 1}));
tests.push(new Test({descr: "LRANGE 10", command: "lrange", args: ["mylist", "0", "9"], pipeline: 50})); tests.push(new Test({descr: 'LRANGE 10', command: 'lrange', args: ['mylist', '0', '9'], pipeline: 50}));
tests.push(new Test({descr: "LRANGE 100", command: "lrange", args: ["mylist", "0", "99"], pipeline: 1})); tests.push(new Test({descr: 'LRANGE 100', command: 'lrange', args: ['mylist', '0', '99'], pipeline: 1}));
tests.push(new Test({descr: "LRANGE 100", command: "lrange", args: ["mylist", "0", "99"], pipeline: 50})); tests.push(new Test({descr: 'LRANGE 100', command: 'lrange', args: ['mylist', '0', '99'], pipeline: 50}));
tests.push(new Test({descr: "SET 4MiB buf", command: "set", args: ["foo_rand000000000002", very_large_buf], pipeline: 1, reqs: 500})); tests.push(new Test({descr: 'SET 4MiB buf', command: 'set', args: ['foo_rand000000000002', very_large_buf], pipeline: 1, reqs: 500}));
tests.push(new Test({descr: "SET 4MiB buf", command: "set", args: ["foo_rand000000000002", very_large_buf], pipeline: 50, reqs: 500})); tests.push(new Test({descr: 'SET 4MiB buf', command: 'set', args: ['foo_rand000000000002', very_large_buf], pipeline: 50, reqs: 500}));
tests.push(new Test({descr: "GET 4MiB str", command: "get", args: ["foo_rand000000000002"], pipeline: 1, reqs: 100})); tests.push(new Test({descr: 'GET 4MiB str', command: 'get', args: ['foo_rand000000000002'], pipeline: 1, reqs: 100}));
tests.push(new Test({descr: "GET 4MiB str", command: "get", args: ["foo_rand000000000002"], pipeline: 50, reqs: 100})); tests.push(new Test({descr: 'GET 4MiB str', command: 'get', args: ['foo_rand000000000002'], pipeline: 50, reqs: 100}));
tests.push(new Test({descr: "GET 4MiB buf", command: "get", args: ["foo_rand000000000002"], pipeline: 1, reqs: 100, client_opts: { return_buffers: true} })); tests.push(new Test({descr: 'GET 4MiB buf', command: 'get', args: ['foo_rand000000000002'], pipeline: 1, reqs: 100, client_opts: { return_buffers: true} }));
tests.push(new Test({descr: "GET 4MiB buf", command: "get", args: ["foo_rand000000000002"], pipeline: 50, reqs: 100, client_opts: { return_buffers: true} })); tests.push(new Test({descr: 'GET 4MiB buf', command: 'get', args: ['foo_rand000000000002'], pipeline: 50, reqs: 100, client_opts: { return_buffers: true} }));
function next() { function next() {
var test = tests.shift(); var test = tests.shift();
@@ -231,7 +231,7 @@ function next() {
next(); next();
}); });
} else { } else {
console.log("End of tests. Total time elapsed:", totalTime, 'ms'); console.log('End of tests. Total time elapsed:', totalTime, 'ms');
process.exit(0); process.exit(0);
} }
} }

View File

@@ -82,7 +82,7 @@ This is the biggest release that node_redis had since it was released in 2010. A
- Fix commands being inconsistent and behaving wrong (@BridgeAR) - Fix commands being inconsistent and behaving wrong (@BridgeAR)
- Channel names with spaces are now properly resubscribed after a reconnection (@pbihler) - Channel names with spaces are now properly resubscribed after a reconnection (@pbihler)
- Do not try to reconnect after the connection timeout has been exceeded (@BridgeAR) - Do not try to reconnect after the connection timeout has been exceeded (@BridgeAR)
- Removed bad .eval implementation (@BridgeAR) - Ensure the execution order is observed if using .eval (@BridgeAR)
- Fix commands not being rejected after calling .quit (@BridgeAR) - Fix commands not being rejected after calling .quit (@BridgeAR)
- Fix .auth calling the callback twice if already connected (@BridgeAR) - Fix .auth calling the callback twice if already connected (@BridgeAR)
- Fix detect_buffers not working in pub sub mode and while monitoring (@BridgeAR) - Fix detect_buffers not working in pub sub mode and while monitoring (@BridgeAR)

View File

@@ -1,7 +1,7 @@
'use strict'; 'use strict';
var redis = require("redis"), var redis = require('redis'),
client = redis.createClient(); client = redis.createClient();
// This command is magical. Client stashes the password and will issue on every connect. // The client stashes the password and will reauthenticate on every connect.
client.auth("somepass"); client.auth('somepass');

View File

@@ -1,6 +1,6 @@
'use strict'; 'use strict';
var redis = require("../index"), var redis = require('../index'),
client = redis.createClient(null, null, { client = redis.createClient(null, null, {
command_queue_high_water: 5, command_queue_high_water: 5,
command_queue_low_water: 1 command_queue_low_water: 1
@@ -9,26 +9,26 @@ var redis = require("../index"),
function op() { function op() {
if (remaining_ops <= 0) { if (remaining_ops <= 0) {
console.error("Finished."); console.error('Finished.');
process.exit(0); process.exit(0);
} }
remaining_ops--; remaining_ops--;
if (client.hset("test hash", "val " + remaining_ops, remaining_ops) === false) { if (client.hset('test hash', 'val ' + remaining_ops, remaining_ops) === false) {
console.log("Pausing at " + remaining_ops); console.log('Pausing at ' + remaining_ops);
paused = true; paused = true;
} else { } else {
process.nextTick(op); process.nextTick(op);
} }
} }
client.on("drain", function () { client.on('drain', function () {
if (paused) { if (paused) {
console.log("Resuming at " + remaining_ops); console.log('Resuming at ' + remaining_ops);
paused = false; paused = false;
process.nextTick(op); process.nextTick(op);
} else { } else {
console.log("Got drain while not paused at " + remaining_ops); console.log('Got drain while not paused at ' + remaining_ops);
} }
}); });

View File

@@ -1,14 +1,14 @@
'use strict'; 'use strict';
var redis = require("../index"), var redis = require('../index'),
client = redis.createClient(); client = redis.createClient();
client.eval("return 100.5", 0, function (err, res) { client.eval('return 100.5', 0, function (err, res) {
console.dir(err); console.dir(err);
console.dir(res); console.dir(res);
}); });
client.eval([ "return 100.5", 0 ], function (err, res) { client.eval([ 'return 100.5', 0 ], function (err, res) {
console.dir(err); console.dir(err);
console.dir(res); console.dir(res);
}); });

View File

@@ -1,14 +1,14 @@
'use strict'; 'use strict';
var redis = require("redis"), var redis = require('redis'),
client = redis.createClient(); client = redis.createClient();
// Extend the RedisClient prototype to add a custom method // Extend the RedisClient prototype to add a custom method
// This one converts the results from "INFO" into a JavaScript Object // This one converts the results from 'INFO' into a JavaScript Object
redis.RedisClient.prototype.parse_info = function (callback) { redis.RedisClient.prototype.parse_info = function (callback) {
this.info(function (err, res) { this.info(function (err, res) {
var lines = res.toString().split("\r\n").sort(); var lines = res.toString().split('\r\n').sort();
var obj = {}; var obj = {};
lines.forEach(function (line) { lines.forEach(function (line) {
var parts = line.split(':'); var parts = line.split(':');

View File

@@ -2,10 +2,10 @@
// Read a file from disk, store it in Redis, then read it back from Redis. // Read a file from disk, store it in Redis, then read it back from Redis.
var redis = require("redis"), var redis = require('redis'),
client = redis.createClient(), client = redis.createClient(),
fs = require("fs"), fs = require('fs'),
filename = "kids_in_cart.jpg"; filename = 'kids_in_cart.jpg';
// Get the file I use for testing like this: // Get the file I use for testing like this:
// curl http://ranney.com/kids_in_cart.jpg -o kids_in_cart.jpg // curl http://ranney.com/kids_in_cart.jpg -o kids_in_cart.jpg
@@ -14,18 +14,18 @@ var redis = require("redis"),
// Read a file from fs, store it in Redis, get it back from Redis, write it back to fs. // Read a file from fs, store it in Redis, get it back from Redis, write it back to fs.
fs.readFile(filename, function (err, data) { fs.readFile(filename, function (err, data) {
if (err) throw err; if (err) throw err;
console.log("Read " + data.length + " bytes from filesystem."); console.log('Read ' + data.length + ' bytes from filesystem.');
client.set(filename, data, redis.print); // set entire file client.set(filename, data, redis.print); // set entire file
client.get(filename, function (err, reply) { // get entire file client.get(filename, function (err, reply) { // get entire file
if (err) { if (err) {
console.log("Get error: " + err); console.log('Get error: ' + err);
} else { } else {
fs.writeFile("duplicate_" + filename, reply, function (err) { fs.writeFile('duplicate_' + filename, reply, function (err) {
if (err) { if (err) {
console.log("Error on write: " + err); console.log('Error on write: ' + err);
} else { } else {
console.log("File written."); console.log('File written.');
} }
client.end(); client.end();
}); });

View File

@@ -1,7 +1,7 @@
'use strict'; 'use strict';
var client = require("redis").createClient(); var client = require('redis').createClient();
client.mget(["sessions started", "sessions started", "foo"], function (err, res) { client.mget(['sessions started', 'sessions started', 'foo'], function (err, res) {
console.dir(res); console.dir(res);
}); });

View File

@@ -1,12 +1,12 @@
'use strict'; 'use strict';
var client = require("../index").createClient(), var client = require('../index').createClient(),
util = require("util"); util = require('util');
client.monitor(function (err, res) { client.monitor(function (err, res) {
console.log("Entering monitoring mode."); console.log('Entering monitoring mode.');
}); });
client.on("monitor", function (time, args) { client.on('monitor', function (time, args) {
console.log(time + ": " + util.inspect(args)); console.log(time + ': ' + util.inspect(args));
}); });

View File

@@ -1,40 +1,40 @@
'use strict'; 'use strict';
var redis = require("redis"), var redis = require('redis'),
client = redis.createClient(), set_size = 20; client = redis.createClient(), set_size = 20;
client.sadd("bigset", "a member"); client.sadd('bigset', 'a member');
client.sadd("bigset", "another member"); client.sadd('bigset', 'another member');
while (set_size > 0) { while (set_size > 0) {
client.sadd("bigset", "member " + set_size); client.sadd('bigset', 'member ' + set_size);
set_size -= 1; set_size -= 1;
} }
// multi chain with an individual callback // multi chain with an individual callback
client.multi() client.multi()
.scard("bigset") .scard('bigset')
.smembers("bigset") .smembers('bigset')
.keys("*", function (err, replies) { .keys('*', function (err, replies) {
client.mget(replies, redis.print); client.mget(replies, redis.print);
}) })
.dbsize() .dbsize()
.exec(function (err, replies) { .exec(function (err, replies) {
console.log("MULTI got " + replies.length + " replies"); console.log('MULTI got ' + replies.length + ' replies');
replies.forEach(function (reply, index) { replies.forEach(function (reply, index) {
console.log("Reply " + index + ": " + reply.toString()); console.log('Reply ' + index + ': ' + reply.toString());
}); });
}); });
client.mset("incr thing", 100, "incr other thing", 1, redis.print); client.mset('incr thing', 100, 'incr other thing', 1, redis.print);
// start a separate multi command queue // start a separate multi command queue
var multi = client.multi(); var multi = client.multi();
multi.incr("incr thing", redis.print); multi.incr('incr thing', redis.print);
multi.incr("incr other thing", redis.print); multi.incr('incr other thing', redis.print);
// runs immediately // runs immediately
client.get("incr thing", redis.print); // 100 client.get('incr thing', redis.print); // 100
// drains multi queue and runs atomically // drains multi queue and runs atomically
multi.exec(function (err, replies) { multi.exec(function (err, replies) {

View File

@@ -1,15 +1,15 @@
'use strict'; 'use strict';
var redis = require("redis"), var redis = require('redis'),
client = redis.createClient(), multi; client = redis.createClient(), multi;
// start a separate command queue for multi // start a separate command queue for multi
multi = client.multi(); multi = client.multi();
multi.incr("incr thing", redis.print); multi.incr('incr thing', redis.print);
multi.incr("incr other thing", redis.print); multi.incr('incr other thing', redis.print);
// runs immediately // runs immediately
client.mset("incr thing", 100, "incr other thing", 1, redis.print); client.mset('incr thing', 100, 'incr other thing', 1, redis.print);
// drains multi queue and runs atomically // drains multi queue and runs atomically
multi.exec(function (err, replies) { multi.exec(function (err, replies) {
@@ -23,9 +23,9 @@ multi.exec(function (err, replies) {
}); });
client.multi([ client.multi([
["mget", "multifoo", "multibar", redis.print], ['mget', 'multifoo', 'multibar', redis.print],
["incr", "multifoo"], ['incr', 'multifoo'],
["incr", "multibar"] ['incr', 'multibar']
]).exec(function (err, replies) { ]).exec(function (err, replies) {
console.log(replies.toString()); console.log(replies.toString());
}); });

View File

@@ -1,33 +1,33 @@
'use strict'; 'use strict';
var redis = require("redis"), var redis = require('redis'),
client1 = redis.createClient(), client1 = redis.createClient(),
client2 = redis.createClient(), client2 = redis.createClient(),
client3 = redis.createClient(), client3 = redis.createClient(),
client4 = redis.createClient(), client4 = redis.createClient(),
msg_count = 0; msg_count = 0;
client1.on("psubscribe", function (pattern, count) { client1.on('psubscribe', function (pattern, count) {
console.log("client1 psubscribed to " + pattern + ", " + count + " total subscriptions"); console.log('client1 psubscribed to ' + pattern + ', ' + count + ' total subscriptions');
client2.publish("channeltwo", "Me!"); client2.publish('channeltwo', 'Me!');
client3.publish("channelthree", "Me too!"); client3.publish('channelthree', 'Me too!');
client4.publish("channelfour", "And me too!"); client4.publish('channelfour', 'And me too!');
}); });
client1.on("punsubscribe", function (pattern, count) { client1.on('punsubscribe', function (pattern, count) {
console.log("client1 punsubscribed from " + pattern + ", " + count + " total subscriptions"); console.log('client1 punsubscribed from ' + pattern + ', ' + count + ' total subscriptions');
client4.end(); client4.end();
client3.end(); client3.end();
client2.end(); client2.end();
client1.end(); client1.end();
}); });
client1.on("pmessage", function (pattern, channel, message) { client1.on('pmessage', function (pattern, channel, message) {
console.log("("+ pattern +")" + " client1 received message on " + channel + ": " + message); console.log('('+ pattern +')' + ' client1 received message on ' + channel + ': ' + message);
msg_count += 1; msg_count += 1;
if (msg_count === 3) { if (msg_count === 3) {
client1.punsubscribe(); client1.punsubscribe();
} }
}); });
client1.psubscribe("channel*"); client1.psubscribe('channel*');

View File

@@ -1,41 +1,41 @@
'use strict'; 'use strict';
var redis = require("redis"), var redis = require('redis'),
client1 = redis.createClient(), msg_count = 0, client1 = redis.createClient(), msg_count = 0,
client2 = redis.createClient(); client2 = redis.createClient();
// Most clients probably don't do much on "subscribe". This example uses it to coordinate things within one program. // Most clients probably don't do much on 'subscribe'. This example uses it to coordinate things within one program.
client1.on("subscribe", function (channel, count) { client1.on('subscribe', function (channel, count) {
console.log("client1 subscribed to " + channel + ", " + count + " total subscriptions"); console.log('client1 subscribed to ' + channel + ', ' + count + ' total subscriptions');
if (count === 2) { if (count === 2) {
client2.publish("a nice channel", "I am sending a message."); client2.publish('a nice channel', 'I am sending a message.');
client2.publish("another one", "I am sending a second message."); client2.publish('another one', 'I am sending a second message.');
client2.publish("a nice channel", "I am sending my last message."); client2.publish('a nice channel', 'I am sending my last message.');
} }
}); });
client1.on("unsubscribe", function (channel, count) { client1.on('unsubscribe', function (channel, count) {
console.log("client1 unsubscribed from " + channel + ", " + count + " total subscriptions"); console.log('client1 unsubscribed from ' + channel + ', ' + count + ' total subscriptions');
if (count === 0) { if (count === 0) {
client2.end(); client2.end();
client1.end(); client1.end();
} }
}); });
client1.on("message", function (channel, message) { client1.on('message', function (channel, message) {
console.log("client1 channel " + channel + ": " + message); console.log('client1 channel ' + channel + ': ' + message);
msg_count += 1; msg_count += 1;
if (msg_count === 3) { if (msg_count === 3) {
client1.unsubscribe(); client1.unsubscribe();
} }
}); });
client1.on("ready", function () { client1.on('ready', function () {
// if you need auth, do it here // if you need auth, do it here
client1.incr("did a thing"); client1.incr('did a thing');
client1.subscribe("a nice channel", "another one"); client1.subscribe('a nice channel', 'another one');
}); });
client2.on("ready", function () { client2.on('ready', function () {
// if you need auth, do it here // if you need auth, do it here
}); });

View File

@@ -1,6 +1,6 @@
'use strict'; 'use strict';
var redis = require("redis"), var redis = require('redis'),
client = redis.createClient(); client = redis.createClient();
var cursor = '0'; var cursor = '0';
@@ -8,8 +8,8 @@ var cursor = '0';
function scan() { function scan() {
client.scan( client.scan(
cursor, cursor,
"MATCH", "q:job:*", 'MATCH', 'q:job:*',
"COUNT", "10", 'COUNT', '10',
function(err, res) { function(err, res) {
if (err) throw err; if (err) throw err;
@@ -17,22 +17,21 @@ function scan() {
cursor = res[0]; cursor = res[0];
// From <http://redis.io/commands/scan>: // From <http://redis.io/commands/scan>:
// "An iteration starts when the cursor is set to 0, // 'An iteration starts when the cursor is set to 0,
// and terminates when the cursor returned by the server is 0." // and terminates when the cursor returned by the server is 0.'
if (cursor === '0') { if (cursor === '0') {
return console.log('Iteration complete'); return console.log('Iteration complete');
} else {
// Remember: more or less than COUNT or no keys may be returned
// See http://redis.io/commands/scan#the-count-option
// Also, SCAN may return the same key multiple times
// See http://redis.io/commands/scan#scan-guarantees
if (res[1].length > 0) {
console.log('Array of matching keys', res[1]);
}
return scan();
} }
// Remember: more or less than COUNT or no keys may be returned
// See http://redis.io/commands/scan#the-count-option
// Also, SCAN may return the same key multiple times
// See http://redis.io/commands/scan#scan-guarantees
if (res[1].length > 0) {
console.log('Array of matching keys', res[1]);
}
return scan();
} }
); );
} }

View File

@@ -1,26 +1,26 @@
'use strict'; 'use strict';
var redis = require("redis"), var redis = require('redis'),
client = redis.createClient(); client = redis.createClient();
client.on("error", function (err) { client.on('error', function (err) {
console.log("error event - " + client.host + ":" + client.port + " - " + err); console.log('error event - ' + client.host + ':' + client.port + ' - ' + err);
}); });
client.set("string key", "string val", redis.print); client.set('string key', 'string val', redis.print);
client.hset("hash key", "hashtest 1", "some value", redis.print); client.hset('hash key', 'hashtest 1', 'some value', redis.print);
client.hset(["hash key", "hashtest 2", "some other value"], redis.print); client.hset(['hash key', 'hashtest 2', 'some other value'], redis.print);
client.hkeys("hash key", function (err, replies) { client.hkeys('hash key', function (err, replies) {
if (err) { if (err) {
return console.error("error response - " + err); return console.error('error response - ' + err);
} }
console.log(replies.length + " replies:"); console.log(replies.length + ' replies:');
replies.forEach(function (reply, i) { replies.forEach(function (reply, i) {
console.log(" " + i + ": " + reply); console.log(' ' + i + ': ' + reply);
}); });
}); });
client.quit(function (err, res) { client.quit(function (err, res) {
console.log("Exiting from quit command."); console.log('Exiting from quit command.');
}); });

View File

@@ -1,19 +1,19 @@
'use strict'; 'use strict';
var redis = require("redis"), var redis = require('redis'),
client = redis.createClient(); client = redis.createClient();
client.sadd("mylist", 1); client.sadd('mylist', 1);
client.sadd("mylist", 2); client.sadd('mylist', 2);
client.sadd("mylist", 3); client.sadd('mylist', 3);
client.set("weight_1", 5); client.set('weight_1', 5);
client.set("weight_2", 500); client.set('weight_2', 500);
client.set("weight_3", 1); client.set('weight_3', 1);
client.set("object_1", "foo"); client.set('object_1', 'foo');
client.set("object_2", "bar"); client.set('object_2', 'bar');
client.set("object_3", "qux"); client.set('object_3', 'qux');
client.sort("mylist", "by", "weight_*", "get", "object_*", redis.print); client.sort('mylist', 'by', 'weight_*', 'get', 'object_*', redis.print);
// Prints Reply: qux,foo,bar // Prints Reply: qux,foo,bar

View File

@@ -1,14 +1,14 @@
'use strict'; 'use strict';
// Sending commands in response to other commands. // Sending commands in response to other commands.
// This example runs "type" against every key in the database // This example runs 'type' against every key in the database
// //
var client = require("redis").createClient(); var client = require('redis').createClient();
client.keys("*", function (err, keys) { client.keys('*', function (err, keys) {
keys.forEach(function (key, pos) { keys.forEach(function (key, pos) {
client.type(key, function (err, keytype) { client.type(key, function (err, keytype) {
console.log(key + " is " + keytype); console.log(key + ' is ' + keytype);
if (pos === (keys.length - 1)) { if (pos === (keys.length - 1)) {
client.quit(); client.quit();
} }

View File

@@ -1,20 +1,16 @@
'use strict'; 'use strict';
var client = require("redis").createClient(); var client = require('redis').createClient();
function print_results(obj) {
console.dir(obj);
}
// build a map of all keys and their types // build a map of all keys and their types
client.keys("*", function (err, all_keys) { client.keys('*', function (err, all_keys) {
var key_types = {}; var key_types = {};
all_keys.forEach(function (key, pos) { // use second arg of forEach to get pos all_keys.forEach(function (key, pos) { // use second arg of forEach to get pos
client.type(key, function (err, type) { client.type(key, function (err, type) {
key_types[key] = type; key_types[key] = type;
if (pos === all_keys.length - 1) { // callbacks all run in order if (pos === all_keys.length - 1) { // callbacks all run in order
print_results(key_types); console.dir(key_types);
} }
}); });
}); });

View File

@@ -1,21 +1,21 @@
'use strict'; 'use strict';
var redis = require("redis"), var redis = require('redis'),
client = redis.createClient("/tmp/redis.sock"), client = redis.createClient('/tmp/redis.sock'),
profiler = require("v8-profiler"); profiler = require('v8-profiler');
client.on("connect", function () { client.on('connect', function () {
console.log("Got Unix socket connection."); console.log('Got Unix socket connection.');
}); });
client.on("error", function (err) { client.on('error', function (err) {
console.log(err.message); console.log(err.message);
}); });
client.set("space chars", "space value"); client.set('space chars', 'space value');
setInterval(function () { setInterval(function () {
client.get("space chars"); client.get('space chars');
}, 100); }, 100);
function done() { function done() {
@@ -26,6 +26,6 @@ function done() {
} }
setTimeout(function () { setTimeout(function () {
console.log("Taking snapshot."); console.log('Taking snapshot.');
profiler.takeSnapshot(); profiler.takeSnapshot();
}, 5000); }, 5000);

View File

@@ -2,12 +2,12 @@
// A simple web server that generates dyanmic content based on responses from Redis // A simple web server that generates dyanmic content based on responses from Redis
var http = require("http"), server, var http = require('http'), server,
redis_client = require("redis").createClient(); redis_client = require('redis').createClient();
server = http.createServer(function (request, response) { server = http.createServer(function (request, response) {
response.writeHead(200, { response.writeHead(200, {
"Content-Type": "text/plain" 'Content-Type': 'text/plain'
}); });
var redis_info, total_requests; var redis_info, total_requests;
@@ -15,18 +15,18 @@ server = http.createServer(function (request, response) {
redis_client.info(function (err, reply) { redis_client.info(function (err, reply) {
redis_info = reply; // stash response in outer scope redis_info = reply; // stash response in outer scope
}); });
redis_client.incr("requests", function (err, reply) { redis_client.incr('requests', function (err, reply) {
total_requests = reply; // stash response in outer scope total_requests = reply; // stash response in outer scope
}); });
redis_client.hincrby("ip", request.connection.remoteAddress, 1); redis_client.hincrby('ip', request.connection.remoteAddress, 1);
redis_client.hgetall("ip", function (err, reply) { redis_client.hgetall('ip', function (err, reply) {
// This is the last reply, so all of the previous replies must have completed already // This is the last reply, so all of the previous replies must have completed already
response.write("This page was generated after talking to redis.\n\n" + response.write('This page was generated after talking to redis.\n\n' +
"Redis info:\n" + redis_info + "\n" + 'Redis info:\n' + redis_info + '\n' +
"Total requests: " + total_requests + "\n\n" + 'Total requests: ' + total_requests + '\n\n' +
"IP count: \n"); 'IP count: \n');
Object.keys(reply).forEach(function (ip) { Object.keys(reply).forEach(function (ip) {
response.write(" " + ip + ": " + reply[ip] + "\n"); response.write(' ' + ip + ': ' + reply[ip] + '\n');
}); });
response.end(); response.end();
}); });

323
index.js
View File

@@ -1,36 +1,36 @@
'use strict'; 'use strict';
var net = require("net"), var net = require('net');
URL = require("url"), var URL = require('url');
util = require("util"), var util = require('util');
utils = require("./lib/utils"), var utils = require('./lib/utils');
Queue = require("./lib/queue"), var Queue = require('./lib/queue');
Command = require("./lib/command"), var Command = require('./lib/command');
events = require("events"), var events = require('events');
parsers = [], var parsers = [];
// This static list of commands is updated from time to time. // This static list of commands is updated from time to time.
// ./lib/commands.js can be updated with generate_commands.js // ./lib/commands.js can be updated with generate_commands.js
commands = require("./lib/commands"), var commands = require('./lib/commands');
connection_id = 0, var connection_id = 0;
default_port = 6379, var default_port = 6379;
default_host = "127.0.0.1", var default_host = '127.0.0.1';
debug = function(msg) { var debug = function(msg) {
if (exports.debug_mode) { if (exports.debug_mode) {
console.error(msg); console.error(msg);
} }
}; };
exports.debug_mode = /\bredis\b/i.test(process.env.NODE_DEBUG); exports.debug_mode = /\bredis\b/i.test(process.env.NODE_DEBUG);
// hiredis might not be installed // hiredis might not be installed
try { try {
parsers.push(require("./lib/parsers/hiredis")); parsers.push(require('./lib/parsers/hiredis'));
} catch (err) { } catch (err) {
/* istanbul ignore next: won't be reached with tests */ /* istanbul ignore next: won't be reached with tests */
debug("Hiredis parser not installed."); debug('Hiredis parser not installed.');
} }
parsers.push(require("./lib/parsers/javascript")); parsers.push(require('./lib/parsers/javascript'));
function RedisClient(stream, options) { function RedisClient(stream, options) {
options = options || {}; options = options || {};
@@ -76,36 +76,35 @@ function RedisClient(stream, options) {
events.EventEmitter.call(this); events.EventEmitter.call(this);
} }
util.inherits(RedisClient, events.EventEmitter); util.inherits(RedisClient, events.EventEmitter);
exports.RedisClient = RedisClient;
RedisClient.prototype.install_stream_listeners = function() { RedisClient.prototype.install_stream_listeners = function() {
var self = this; var self = this;
this.stream.on("connect", function () { this.stream.on('connect', function () {
self.on_connect(); self.on_connect();
}); });
this.stream.on("data", function (buffer_from_socket) { this.stream.on('data', function (buffer_from_socket) {
// The data.toString() has a significant impact on big chunks and therefor this should only be used if necessary // The data.toString() has a significant impact on big chunks and therefor this should only be used if necessary
// debug("Net read " + this.address + " id " + this.connection_id + ": " + data.toString()); // debug('Net read ' + this.address + ' id ' + this.connection_id + ': ' + data.toString());
self.reply_parser.execute(buffer_from_socket); self.reply_parser.execute(buffer_from_socket);
}); });
this.stream.on("error", function (err) { this.stream.on('error', function (err) {
self.on_error(err); self.on_error(err);
}); });
this.stream.on("close", function () { this.stream.on('close', function () {
self.connection_gone("close"); self.connection_gone('close');
}); });
this.stream.on("end", function () { this.stream.on('end', function () {
self.connection_gone("end"); self.connection_gone('end');
}); });
this.stream.on("drain", function () { this.stream.on('drain', function () {
self.should_buffer = false; self.should_buffer = false;
self.emit("drain"); self.emit('drain');
}); });
}; };
@@ -122,8 +121,8 @@ RedisClient.prototype.unref = function () {
debug("Unref'ing the socket connection"); debug("Unref'ing the socket connection");
this.stream.unref(); this.stream.unref();
} else { } else {
debug("Not connected yet, will unref later"); debug('Not connected yet, will unref later');
this.once("connect", function () { this.once('connect', function () {
this.unref(); this.unref();
}); });
} }
@@ -134,7 +133,7 @@ RedisClient.prototype.flush_and_error = function (error) {
var command_obj; var command_obj;
while (command_obj = this.offline_queue.shift()) { while (command_obj = this.offline_queue.shift()) {
if (typeof command_obj.callback === "function") { if (typeof command_obj.callback === 'function') {
error.command = command_obj.command.toUpperCase(); error.command = command_obj.command.toUpperCase();
command_obj.callback(error); command_obj.callback(error);
} }
@@ -142,7 +141,7 @@ RedisClient.prototype.flush_and_error = function (error) {
this.offline_queue = new Queue(); this.offline_queue = new Queue();
while (command_obj = this.command_queue.shift()) { while (command_obj = this.command_queue.shift()) {
if (typeof command_obj.callback === "function") { if (typeof command_obj.callback === 'function') {
error.command = command_obj.command.toUpperCase(); error.command = command_obj.command.toUpperCase();
command_obj.callback(error); command_obj.callback(error);
} }
@@ -155,16 +154,16 @@ RedisClient.prototype.on_error = function (err) {
return; return;
} }
err.message = "Redis connection to " + this.address + " failed - " + err.message; err.message = 'Redis connection to ' + this.address + ' failed - ' + err.message;
debug(err.message); debug(err.message);
this.connected = false; this.connected = false;
this.ready = false; this.ready = false;
this.emit("error", err); this.emit('error', err);
// "error" events get turned into exceptions if they aren't listened for. If the user handled this error // 'error' events get turned into exceptions if they aren't listened for. If the user handled this error
// then we should try to reconnect. // then we should try to reconnect.
this.connection_gone("error"); this.connection_gone('error');
}; };
var noPasswordIsSet = /no password is set/; var noPasswordIsSet = /no password is set/;
@@ -173,35 +172,35 @@ var loading = /LOADING/;
RedisClient.prototype.do_auth = function () { RedisClient.prototype.do_auth = function () {
var self = this; var self = this;
debug("Sending auth to " + self.address + " id " + self.connection_id); debug('Sending auth to ' + self.address + ' id ' + self.connection_id);
self.send_anyway = true; self.send_anyway = true;
self.send_command("auth", [this.auth_pass], function (err, res) { self.send_command('auth', [this.auth_pass], function (err, res) {
if (err) { if (err) {
/* istanbul ignore if: this is almost impossible to test */ /* istanbul ignore if: this is almost impossible to test */
if (loading.test(err.message)) { if (loading.test(err.message)) {
// If redis is still loading the db, it will not authenticate and everything else will fail // If redis is still loading the db, it will not authenticate and everything else will fail
debug("Redis still loading, trying to authenticate later"); debug('Redis still loading, trying to authenticate later');
setTimeout(function () { setTimeout(function () {
self.do_auth(); self.do_auth();
}, 333); }, 333);
return; return;
} else if (noPasswordIsSet.test(err.message)) { } else if (noPasswordIsSet.test(err.message)) {
debug("Warning: Redis server does not require a password, but a password was supplied."); debug('Warning: Redis server does not require a password, but a password was supplied.');
err = null; err = null;
res = "OK"; res = 'OK';
} else if (self.auth_callback) { } else if (self.auth_callback) {
self.auth_callback(err); self.auth_callback(err);
self.auth_callback = null; self.auth_callback = null;
return; return;
} else { } else {
self.emit("error", err); self.emit('error', err);
return; return;
} }
} }
res = res.toString(); res = res.toString();
debug("Auth succeeded " + self.address + " id " + self.connection_id); debug('Auth succeeded ' + self.address + ' id ' + self.connection_id);
if (self.auth_callback) { if (self.auth_callback) {
self.auth_callback(null, res); self.auth_callback(null, res);
@@ -209,7 +208,7 @@ RedisClient.prototype.do_auth = function () {
} }
// Now we are really connected // Now we are really connected
self.emit("connect"); self.emit('connect');
self.initialize_retry_vars(); self.initialize_retry_vars();
if (self.options.no_ready_check) { if (self.options.no_ready_check) {
@@ -222,7 +221,7 @@ RedisClient.prototype.do_auth = function () {
}; };
RedisClient.prototype.on_connect = function () { RedisClient.prototype.on_connect = function () {
debug("Stream connected " + this.address + " id " + this.connection_id); debug('Stream connected ' + this.address + ' id ' + this.connection_id);
this.connected = true; this.connected = true;
this.ready = false; this.ready = false;
@@ -240,7 +239,7 @@ RedisClient.prototype.on_connect = function () {
if (typeof this.auth_pass === 'string') { if (typeof this.auth_pass === 'string') {
this.do_auth(); this.do_auth();
} else { } else {
this.emit("connect"); this.emit('connect');
this.initialize_retry_vars(); this.initialize_retry_vars();
if (this.options.no_ready_check) { if (this.options.no_ready_check) {
@@ -258,7 +257,7 @@ RedisClient.prototype.init_parser = function () {
if (!parsers.some(function (parser) { if (!parsers.some(function (parser) {
if (parser.name === self.options.parser) { if (parser.name === self.options.parser) {
self.parser_module = parser; self.parser_module = parser;
debug("Using parser module: " + self.parser_module.name); debug('Using parser module: ' + self.parser_module.name);
return true; return true;
} }
})) { })) {
@@ -267,7 +266,7 @@ RedisClient.prototype.init_parser = function () {
throw new Error("Couldn't find named parser " + self.options.parser + " on this system"); throw new Error("Couldn't find named parser " + self.options.parser + " on this system");
} }
} else { } else {
debug("Using default parser module: " + parsers[0].name); debug('Using default parser module: ' + parsers[0].name);
this.parser_module = parsers[0]; this.parser_module = parsers[0];
} }
@@ -310,39 +309,39 @@ RedisClient.prototype.on_ready = function () {
this.pub_sub_mode = pub_sub_mode; this.pub_sub_mode = pub_sub_mode;
} }
if (this.pub_sub_mode === true) { if (this.pub_sub_mode === true) {
// only emit "ready" when all subscriptions were made again // only emit 'ready' when all subscriptions were made again
var callback_count = 0; var callback_count = 0;
var callback = function () { var callback = function () {
callback_count--; callback_count--;
if (callback_count === 0) { if (callback_count === 0) {
self.emit("ready"); self.emit('ready');
} }
}; };
if (this.options.disable_resubscribing) { if (this.options.disable_resubscribing) {
return; return;
} }
Object.keys(this.subscription_set).forEach(function (key) { Object.keys(this.subscription_set).forEach(function (key) {
var space_index = key.indexOf(" "); var space_index = key.indexOf(' ');
var parts = [key.slice(0, space_index), key.slice(space_index + 1)]; var parts = [key.slice(0, space_index), key.slice(space_index + 1)];
debug("Sending pub/sub on_ready " + parts[0] + ", " + parts[1]); debug('Sending pub/sub on_ready ' + parts[0] + ', ' + parts[1]);
callback_count++; callback_count++;
self.send_command(parts[0] + "scribe", [parts[1]], callback); self.send_command(parts[0] + 'scribe', [parts[1]], callback);
}); });
return; return;
} }
if (this.monitoring) { if (this.monitoring) {
this.send_command("monitor", []); this.send_command('monitor', []);
} else { } else {
this.send_offline_queue(); this.send_offline_queue();
} }
this.emit("ready"); this.emit('ready');
}; };
RedisClient.prototype.on_info_cmd = function (err, res) { RedisClient.prototype.on_info_cmd = function (err, res) {
if (err) { if (err) {
err.message = "Ready check failed: " + err.message; err.message = 'Ready check failed: ' + err.message;
this.emit("error", err); this.emit('error', err);
return; return;
} }
@@ -356,7 +355,7 @@ RedisClient.prototype.on_info_cmd = function (err, res) {
var self = this; var self = this;
var obj = {}; var obj = {};
var lines = res.toString().split("\r\n"); var lines = res.toString().split('\r\n');
var i = 0; var i = 0;
var key = 'db' + i; var key = 'db' + i;
var line, retry_time, parts, sub_parts; var line, retry_time, parts, sub_parts;
@@ -390,15 +389,15 @@ RedisClient.prototype.on_info_cmd = function (err, res) {
// expose info key/vals to users // expose info key/vals to users
this.server_info = obj; this.server_info = obj;
if (!obj.loading || obj.loading === "0") { if (!obj.loading || obj.loading === '0') {
debug("Redis server ready."); debug('Redis server ready.');
this.on_ready(); this.on_ready();
} else { } else {
retry_time = obj.loading_eta_seconds * 1000; retry_time = obj.loading_eta_seconds * 1000;
if (retry_time > 1000) { if (retry_time > 1000) {
retry_time = 1000; retry_time = 1000;
} }
debug("Redis server still loading, trying again in " + retry_time); debug('Redis server still loading, trying again in ' + retry_time);
setTimeout(function () { setTimeout(function () {
self.ready_check(); self.ready_check();
}, retry_time); }, retry_time);
@@ -408,9 +407,9 @@ RedisClient.prototype.on_info_cmd = function (err, res) {
RedisClient.prototype.ready_check = function () { RedisClient.prototype.ready_check = function () {
var self = this; var self = this;
debug("Checking server ready state..."); debug('Checking server ready state...');
this.send_anyway = true; // secret flag to send_command to send something even if not "ready" this.send_anyway = true; // secret flag to send_command to send something even if not 'ready'
this.info(function (err, res) { this.info(function (err, res) {
self.on_info_cmd(err, res); self.on_info_cmd(err, res);
}); });
@@ -421,7 +420,7 @@ RedisClient.prototype.send_offline_queue = function () {
var command_obj, buffered_writes = 0; var command_obj, buffered_writes = 0;
while (command_obj = this.offline_queue.shift()) { while (command_obj = this.offline_queue.shift()) {
debug("Sending offline command: " + command_obj.command); debug('Sending offline command: ' + command_obj.command);
buffered_writes += !this.send_command(command_obj.command, command_obj.args, command_obj.callback); buffered_writes += !this.send_command(command_obj.command, command_obj.args, command_obj.callback);
} }
this.offline_queue = new Queue(); this.offline_queue = new Queue();
@@ -429,14 +428,14 @@ RedisClient.prototype.send_offline_queue = function () {
if (!buffered_writes) { if (!buffered_writes) {
this.should_buffer = false; this.should_buffer = false;
this.emit("drain"); this.emit('drain');
} }
}; };
var retry_connection = function (self) { var retry_connection = function (self) {
debug("Retrying connection..."); debug('Retrying connection...');
self.emit("reconnecting", { self.emit('reconnecting', {
delay: self.retry_delay, delay: self.retry_delay,
attempt: self.attempts attempt: self.attempts
}); });
@@ -457,7 +456,7 @@ RedisClient.prototype.connection_gone = function (why) {
return; return;
} }
debug("Redis connection is gone from " + why + " event."); debug('Redis connection is gone from ' + why + ' event.');
this.connected = false; this.connected = false;
this.ready = false; this.ready = false;
@@ -475,14 +474,14 @@ RedisClient.prototype.connection_gone = function (why) {
// since we are collapsing end and close, users don't expect to be called twice // since we are collapsing end and close, users don't expect to be called twice
if (!this.emitted_end) { if (!this.emitted_end) {
this.emit("end"); this.emit('end');
this.emitted_end = true; this.emitted_end = true;
} }
// If this is a requested shutdown, then don't retry // If this is a requested shutdown, then don't retry
if (this.closing) { if (this.closing) {
debug("Connection ended from quit command, not retrying."); debug('Connection ended from quit command, not retrying.');
this.flush_and_error(new Error("Redis connection gone from " + why + " event.")); this.flush_and_error(new Error('Redis connection gone from ' + why + ' event.'));
return; return;
} }
@@ -490,7 +489,7 @@ RedisClient.prototype.connection_gone = function (why) {
var message = this.retry_totaltime >= this.connect_timeout ? var message = this.retry_totaltime >= this.connect_timeout ?
'connection timeout exceeded.' : 'connection timeout exceeded.' :
'maximum connection attempts exceeded.'; 'maximum connection attempts exceeded.';
var error = new Error("Redis connection in broken state: " + message); var error = new Error('Redis connection in broken state: ' + message);
error.code = 'CONNECTION_BROKEN'; error.code = 'CONNECTION_BROKEN';
this.flush_and_error(error); this.flush_and_error(error);
this.emit('error', error); this.emit('error', error);
@@ -527,11 +526,11 @@ RedisClient.prototype.return_error = function (err) {
if (this.pub_sub_mode === false && queue_len === 0) { if (this.pub_sub_mode === false && queue_len === 0) {
this.command_queue = new Queue(); this.command_queue = new Queue();
this.emit("idle"); this.emit('idle');
} }
if (this.should_buffer && queue_len <= this.command_queue_low_water) { if (this.should_buffer && queue_len <= this.command_queue_low_water) {
this.emit("drain"); this.emit('drain');
this.should_buffer = false; this.should_buffer = false;
} }
@@ -545,7 +544,7 @@ RedisClient.prototype.return_error = function (err) {
RedisClient.prototype.return_reply = function (reply) { RedisClient.prototype.return_reply = function (reply) {
var command_obj, len, type, timestamp, argindex, args, queue_len; var command_obj, len, type, timestamp, argindex, args, queue_len;
// If the "reply" here is actually a message received asynchronously due to a // If the 'reply' here is actually a message received asynchronously due to a
// pubsub subscription, don't pop the command queue as we'll only be consuming // pubsub subscription, don't pop the command queue as we'll only be consuming
// the head command prematurely. // the head command prematurely.
if (this.pub_sub_mode && Array.isArray(reply) && reply[0]) { if (this.pub_sub_mode && Array.isArray(reply) && reply[0]) {
@@ -553,7 +552,7 @@ RedisClient.prototype.return_reply = function (reply) {
} }
if (this.pub_sub_mode && (type === 'message' || type === 'pmessage')) { if (this.pub_sub_mode && (type === 'message' || type === 'pmessage')) {
debug("Received pubsub message"); debug('Received pubsub message');
} else { } else {
command_obj = this.command_queue.shift(); command_obj = this.command_queue.shift();
} }
@@ -562,15 +561,15 @@ RedisClient.prototype.return_reply = function (reply) {
if (this.pub_sub_mode === false && queue_len === 0) { if (this.pub_sub_mode === false && queue_len === 0) {
this.command_queue = new Queue(); // explicitly reclaim storage from old Queue this.command_queue = new Queue(); // explicitly reclaim storage from old Queue
this.emit("idle"); this.emit('idle');
} }
if (this.should_buffer && queue_len <= this.command_queue_low_water) { if (this.should_buffer && queue_len <= this.command_queue_low_water) {
this.emit("drain"); this.emit('drain');
this.should_buffer = false; this.should_buffer = false;
} }
if (command_obj && !command_obj.sub_command) { if (command_obj && !command_obj.sub_command) {
if (typeof command_obj.callback === "function") { if (typeof command_obj.callback === 'function') {
if ('exec' !== command_obj.command) { if ('exec' !== command_obj.command) {
if (this.options.detect_buffers && command_obj.buffer_args === false) { if (this.options.detect_buffers && command_obj.buffer_args === false) {
// If detect_buffers option was specified, then the reply from the parser will be Buffers. // If detect_buffers option was specified, then the reply from the parser will be Buffers.
@@ -586,7 +585,7 @@ RedisClient.prototype.return_reply = function (reply) {
command_obj.callback(null, reply); command_obj.callback(null, reply);
} else { } else {
debug("No callback for reply"); debug('No callback for reply');
} }
} else if (this.pub_sub_mode || command_obj && command_obj.sub_command) { } else if (this.pub_sub_mode || command_obj && command_obj.sub_command) {
if (Array.isArray(reply)) { if (Array.isArray(reply)) {
@@ -595,29 +594,29 @@ RedisClient.prototype.return_reply = function (reply) {
} }
type = reply[0].toString(); type = reply[0].toString();
if (type === "message") { if (type === 'message') {
this.emit("message", reply[1], reply[2]); // channel, message this.emit('message', reply[1], reply[2]); // channel, message
} else if (type === "pmessage") { } else if (type === 'pmessage') {
this.emit("pmessage", reply[1], reply[2], reply[3]); // pattern, channel, message this.emit('pmessage', reply[1], reply[2], reply[3]); // pattern, channel, message
} else if (type === "subscribe" || type === "unsubscribe" || type === "psubscribe" || type === "punsubscribe") { } else if (type === 'subscribe' || type === 'unsubscribe' || type === 'psubscribe' || type === 'punsubscribe') {
if (reply[2] === 0) { if (reply[2] === 0) {
this.pub_sub_mode = false; this.pub_sub_mode = false;
debug("All subscriptions removed, exiting pub/sub mode"); debug('All subscriptions removed, exiting pub/sub mode');
} else { } else {
this.pub_sub_mode = true; this.pub_sub_mode = true;
} }
// subscribe commands take an optional callback and also emit an event, but only the first response is included in the callback // subscribe commands take an optional callback and also emit an event, but only the first response is included in the callback
// TODO - document this or fix it so it works in a more obvious way // TODO - document this or fix it so it works in a more obvious way
if (command_obj && typeof command_obj.callback === "function") { if (command_obj && typeof command_obj.callback === 'function') {
command_obj.callback(null, reply[1]); command_obj.callback(null, reply[1]);
} }
this.emit(type, reply[1], reply[2]); // channel, count this.emit(type, reply[1], reply[2]); // channel, count
} else { } else {
this.emit("error", new Error("subscriptions are active but got unknown reply type " + type)); this.emit('error', new Error('subscriptions are active but got unknown reply type ' + type));
return; return;
} }
} else if (!this.closing) { } else if (!this.closing) {
this.emit("error", new Error("subscriptions are active but got an invalid reply: " + reply)); this.emit('error', new Error('subscriptions are active but got an invalid reply: ' + reply));
return; return;
} }
} }
@@ -627,29 +626,29 @@ RedisClient.prototype.return_reply = function (reply) {
reply = reply.toString(); reply = reply.toString();
} }
// If in monitoring mode only two commands are valid ones: AUTH and MONITOR wich reply with OK // If in monitoring mode only two commands are valid ones: AUTH and MONITOR wich reply with OK
len = reply.indexOf(" "); len = reply.indexOf(' ');
timestamp = reply.slice(0, len); timestamp = reply.slice(0, len);
argindex = reply.indexOf('"'); argindex = reply.indexOf('"');
args = reply.slice(argindex + 1, -1).split('" "').map(function (elem) { args = reply.slice(argindex + 1, -1).split('" "').map(function (elem) {
return elem.replace(/\\"/g, '"'); return elem.replace(/\\"/g, '"');
}); });
this.emit("monitor", timestamp, args); this.emit('monitor', timestamp, args);
} else { } else {
var err = new Error("node_redis command queue state error. If you can reproduce this, please report it."); var err = new Error('node_redis command queue state error. If you can reproduce this, please report it.');
err.command_obj = command_obj; err.command_obj = command_obj;
this.emit("error", err); this.emit('error', err);
} }
}; };
RedisClient.prototype.send_command = function (command, args, callback) { RedisClient.prototype.send_command = function (command, args, callback) {
var arg, command_obj, i, elem_count, buffer_args, stream = this.stream, command_str = "", buffered_writes = 0, err; var arg, command_obj, i, elem_count, buffer_args, stream = this.stream, command_str = '', buffered_writes = 0, err;
if (args === undefined) { if (args === undefined) {
args = []; args = [];
} else if (!callback) { } else if (!callback) {
if (typeof args[args.length - 1] === "function") { if (typeof args[args.length - 1] === 'function') {
callback = args.pop(); callback = args.pop();
} else if (typeof args[args.length - 1] === "undefined") { } else if (typeof args[args.length - 1] === 'undefined') {
args.pop(); args.pop();
} }
} }
@@ -667,7 +666,7 @@ RedisClient.prototype.send_command = function (command, args, callback) {
if (callback) { if (callback) {
return callback && callback(err); return callback && callback(err);
} }
this.emit("error", err); this.emit('error', err);
return; return;
} }
} }
@@ -686,9 +685,9 @@ RedisClient.prototype.send_command = function (command, args, callback) {
if (this.closing || !this.enable_offline_queue) { if (this.closing || !this.enable_offline_queue) {
command = command.toUpperCase(); command = command.toUpperCase();
if (!this.closing) { if (!this.closing) {
err = new Error(command + ' can\'t be processed. Stream not writeable and enable_offline_queue is deactivated.'); err = new Error(command + " can't be processed. Stream not writeable and enable_offline_queue is deactivated.");
} else { } else {
err = new Error(command + ' can\'t be processed. The connection has already been closed.'); err = new Error(command + " can't be processed. The connection has already been closed.");
} }
err.command = command; err.command = command;
if (callback) { if (callback) {
@@ -697,23 +696,23 @@ RedisClient.prototype.send_command = function (command, args, callback) {
this.emit('error', err); this.emit('error', err);
} }
} else { } else {
debug("Queueing " + command + " for next server connection."); debug('Queueing ' + command + ' for next server connection.');
this.offline_queue.push(command_obj); this.offline_queue.push(command_obj);
this.should_buffer = true; this.should_buffer = true;
} }
return; return;
} }
if (command === "subscribe" || command === "psubscribe" || command === "unsubscribe" || command === "punsubscribe") { if (command === 'subscribe' || command === 'psubscribe' || command === 'unsubscribe' || command === 'punsubscribe') {
this.pub_sub_command(command_obj); this.pub_sub_command(command_obj);
} else if (command === "monitor") { } else if (command === 'monitor') {
this.monitoring = true; this.monitoring = true;
} else if (command === "quit") { } else if (command === 'quit') {
this.closing = true; this.closing = true;
} else if (this.pub_sub_mode === true) { } else if (this.pub_sub_mode === true) {
err = new Error("Connection in subscriber mode, only subscriber commands may be used"); err = new Error('Connection in subscriber mode, only subscriber commands may be used');
err.command = command.toUpperCase(); err.command = command.toUpperCase();
this.emit("error", err); this.emit('error', err);
return; return;
} }
this.command_queue.push(command_obj); this.command_queue.push(command_obj);
@@ -721,23 +720,23 @@ RedisClient.prototype.send_command = function (command, args, callback) {
elem_count = args.length + 1; elem_count = args.length + 1;
// Always use "Multi bulk commands", but if passed any Buffer args, then do multiple writes, one for each arg. // Always use 'Multi bulk commands', but if passed any Buffer args, then do multiple writes, one for each arg.
// This means that using Buffers in commands is going to be slower, so use Strings if you don't already have a Buffer. // This means that using Buffers in commands is going to be slower, so use Strings if you don't already have a Buffer.
command_str = "*" + elem_count + "\r\n$" + command.length + "\r\n" + command + "\r\n"; command_str = '*' + elem_count + '\r\n$' + command.length + '\r\n' + command + '\r\n';
if (!buffer_args) { // Build up a string and send entire command in one write if (!buffer_args) { // Build up a string and send entire command in one write
for (i = 0; i < args.length; i += 1) { for (i = 0; i < args.length; i += 1) {
arg = args[i]; arg = args[i];
if (typeof arg !== "string") { if (typeof arg !== 'string') {
arg = String(arg); arg = String(arg);
} }
command_str += "$" + Buffer.byteLength(arg) + "\r\n" + arg + "\r\n"; command_str += '$' + Buffer.byteLength(arg) + '\r\n' + arg + '\r\n';
} }
debug("Send " + this.address + " id " + this.connection_id + ": " + command_str); debug('Send ' + this.address + ' id ' + this.connection_id + ': ' + command_str);
buffered_writes += !stream.write(command_str); buffered_writes += !stream.write(command_str);
} else { } else {
debug("Send command (" + command_str + ") has Buffer arguments"); debug('Send command (' + command_str + ') has Buffer arguments');
buffered_writes += !stream.write(command_str); buffered_writes += !stream.write(command_str);
for (i = 0; i < args.length; i += 1) { for (i = 0; i < args.length; i += 1) {
@@ -748,21 +747,21 @@ RedisClient.prototype.send_command = function (command, args, callback) {
if (Buffer.isBuffer(arg)) { if (Buffer.isBuffer(arg)) {
if (arg.length === 0) { if (arg.length === 0) {
debug("send_command: using empty string for 0 length buffer"); debug('send_command: using empty string for 0 length buffer');
buffered_writes += !stream.write("$0\r\n\r\n"); buffered_writes += !stream.write('$0\r\n\r\n');
} else { } else {
buffered_writes += !stream.write("$" + arg.length + "\r\n"); buffered_writes += !stream.write('$' + arg.length + '\r\n');
buffered_writes += !stream.write(arg); buffered_writes += !stream.write(arg);
buffered_writes += !stream.write("\r\n"); buffered_writes += !stream.write('\r\n');
debug("send_command: buffer send " + arg.length + " bytes"); debug('send_command: buffer send ' + arg.length + ' bytes');
} }
} else { } else {
debug("send_command: string send " + Buffer.byteLength(arg) + " bytes: " + arg); debug('send_command: string send ' + Buffer.byteLength(arg) + ' bytes: ' + arg);
buffered_writes += !stream.write("$" + Buffer.byteLength(arg) + "\r\n" + arg + "\r\n"); buffered_writes += !stream.write('$' + Buffer.byteLength(arg) + '\r\n' + arg + '\r\n');
} }
} }
} }
debug("send_command buffered_writes: " + buffered_writes, " should_buffer: " + this.should_buffer); debug('send_command buffered_writes: ' + buffered_writes, ' should_buffer: ' + this.should_buffer);
if (buffered_writes || this.command_queue.length >= this.command_queue_high_water) { if (buffered_writes || this.command_queue.length >= this.command_queue_high_water) {
this.should_buffer = true; this.should_buffer = true;
} }
@@ -773,30 +772,30 @@ RedisClient.prototype.pub_sub_command = function (command_obj) {
var i, key, command, args; var i, key, command, args;
if (this.pub_sub_mode === false) { if (this.pub_sub_mode === false) {
debug("Entering pub/sub mode from " + command_obj.command); debug('Entering pub/sub mode from ' + command_obj.command);
} }
this.pub_sub_mode = true; this.pub_sub_mode = true;
command_obj.sub_command = true; command_obj.sub_command = true;
command = command_obj.command; command = command_obj.command;
args = command_obj.args; args = command_obj.args;
if (command === "subscribe" || command === "psubscribe") { if (command === 'subscribe' || command === 'psubscribe') {
if (command === "subscribe") { if (command === 'subscribe') {
key = "sub"; key = 'sub';
} else { } else {
key = "psub"; key = 'psub';
} }
for (i = 0; i < args.length; i++) { for (i = 0; i < args.length; i++) {
this.subscription_set[key + " " + args[i]] = true; this.subscription_set[key + ' ' + args[i]] = true;
} }
} else { } else {
if (command === "unsubscribe") { if (command === 'unsubscribe') {
key = "sub"; key = 'sub';
} else { } else {
key = "psub"; key = 'psub';
} }
for (i = 0; i < args.length; i++) { for (i = 0; i < args.length; i++) {
delete this.subscription_set[key + " " + args[i]]; delete this.subscription_set[key + ' ' + args[i]];
} }
} }
}; };
@@ -809,7 +808,7 @@ RedisClient.prototype.end = function (flush) {
clearTimeout(this.retry_timer); clearTimeout(this.retry_timer);
this.retry_timer = null; this.retry_timer = null;
} }
this.stream.on("error", function noop(){}); this.stream.on('error', function noop(){});
// Flush queue if wanted // Flush queue if wanted
if (flush) { if (flush) {
@@ -824,7 +823,7 @@ RedisClient.prototype.end = function (flush) {
function Multi(client, args) { function Multi(client, args) {
this._client = client; this._client = client;
this.queue = [["multi"]]; this.queue = [['multi']];
var command, tmp_args; var command, tmp_args;
if (Array.isArray(args)) { if (Array.isArray(args)) {
while (tmp_args = args.shift()) { while (tmp_args = args.shift()) {
@@ -839,6 +838,10 @@ function Multi(client, args) {
} }
} }
RedisClient.prototype.multi = RedisClient.prototype.MULTI = function (args) {
return new Multi(this, args);
};
commands.forEach(function (fullCommand) { commands.forEach(function (fullCommand) {
var command = fullCommand.split(' ')[0]; var command = fullCommand.split(' ')[0];
@@ -923,10 +926,10 @@ RedisClient.prototype.auth = RedisClient.prototype.AUTH = function (pass, callba
return; return;
} }
this.auth_pass = pass; this.auth_pass = pass;
debug("Saving auth as " + this.auth_pass); debug('Saving auth as ' + this.auth_pass);
// Only run the callback once. So do not safe it if already connected // Only run the callback once. So do not safe it if already connected
if (this.connected) { if (this.connected) {
this.send_command("auth", [this.auth_pass], callback); this.send_command('auth', [this.auth_pass], callback);
} else { } else {
this.auth_callback = callback; this.auth_callback = callback;
} }
@@ -935,18 +938,18 @@ RedisClient.prototype.auth = RedisClient.prototype.AUTH = function (pass, callba
RedisClient.prototype.hmset = RedisClient.prototype.HMSET = function (key, args, callback) { RedisClient.prototype.hmset = RedisClient.prototype.HMSET = function (key, args, callback) {
var field, tmp_args; var field, tmp_args;
if (Array.isArray(key)) { if (Array.isArray(key)) {
return this.send_command("hmset", key, args); return this.send_command('hmset', key, args);
} }
if (Array.isArray(args)) { if (Array.isArray(args)) {
return this.send_command("hmset", [key].concat(args), callback); return this.send_command('hmset', [key].concat(args), callback);
} }
if (typeof args === "object") { if (typeof args === 'object') {
// User does: client.hmset(key, {key1: val1, key2: val2}) // User does: client.hmset(key, {key1: val1, key2: val2})
// assuming key is a string, i.e. email address // assuming key is a string, i.e. email address
// if key is a number, i.e. timestamp, convert to string // if key is a number, i.e. timestamp, convert to string
// TODO: This seems random and no other command get's the key converted => either all or none should behave like this // TODO: This seems random and no other command get's the key converted => either all or none should behave like this
if (typeof key !== "string") { if (typeof key !== 'string') {
key = key.toString(); key = key.toString();
} }
tmp_args = [key]; tmp_args = [key];
@@ -954,9 +957,9 @@ RedisClient.prototype.hmset = RedisClient.prototype.HMSET = function (key, args,
while (field = fields.shift()) { while (field = fields.shift()) {
tmp_args.push(field, args[field]); tmp_args.push(field, args[field]);
} }
return this.send_command("hmset", tmp_args, callback); return this.send_command('hmset', tmp_args, callback);
} }
return this.send_command("hmset", utils.to_array(arguments)); return this.send_command('hmset', utils.to_array(arguments));
}; };
Multi.prototype.hmset = Multi.prototype.HMSET = function (key, args, callback) { Multi.prototype.hmset = Multi.prototype.HMSET = function (key, args, callback) {
@@ -971,11 +974,11 @@ Multi.prototype.hmset = Multi.prototype.HMSET = function (key, args, callback) {
args = args.concat([callback]); args = args.concat([callback]);
} }
tmp_args = ['hmset', key].concat(args); tmp_args = ['hmset', key].concat(args);
} else if (typeof args === "object") { } else if (typeof args === 'object') {
if (typeof key !== "string") { if (typeof key !== 'string') {
key = key.toString(); key = key.toString();
} }
tmp_args = ["hmset", key]; tmp_args = ['hmset', key];
var fields = Object.keys(args); var fields = Object.keys(args);
while (field = fields.shift()) { while (field = fields.shift()) {
tmp_args.push(field); tmp_args.push(field);
@@ -986,7 +989,7 @@ Multi.prototype.hmset = Multi.prototype.HMSET = function (key, args, callback) {
} }
} else { } else {
tmp_args = utils.to_array(arguments); tmp_args = utils.to_array(arguments);
tmp_args.unshift("hmset"); tmp_args.unshift('hmset');
} }
this.queue.push(tmp_args); this.queue.push(tmp_args);
return this; return this;
@@ -1010,12 +1013,12 @@ Multi.prototype.exec = Multi.prototype.EXEC = function (callback) {
this.errors = []; this.errors = [];
this.callback = callback; this.callback = callback;
this.wants_buffers = new Array(this.queue.length); this.wants_buffers = new Array(this.queue.length);
// drain queue, callback will catch "QUEUED" or error // drain queue, callback will catch 'QUEUED' or error
for (var index = 0; index < this.queue.length; index++) { for (var index = 0; index < this.queue.length; index++) {
var args = this.queue[index].slice(0); var args = this.queue[index].slice(0);
var command = args.shift(); var command = args.shift();
var cb; var cb;
if (typeof args[args.length - 1] === "function") { if (typeof args[args.length - 1] === 'function') {
cb = args.pop(); cb = args.pop();
} }
// Keep track of who wants buffer responses: // Keep track of who wants buffer responses:
@@ -1066,13 +1069,13 @@ Multi.prototype.execute_callback = function (err, replies) {
if (this._client.options.detect_buffers && this.wants_buffers[i + 1] === false) { if (this._client.options.detect_buffers && this.wants_buffers[i + 1] === false) {
replies[i] = utils.reply_to_strings(replies[i]); replies[i] = utils.reply_to_strings(replies[i]);
} }
if (args[0] === "hgetall") { if (args[0] === 'hgetall') {
// TODO - confusing and error-prone that hgetall is special cased in two places // TODO - confusing and error-prone that hgetall is special cased in two places
replies[i] = utils.reply_to_object(replies[i]); replies[i] = utils.reply_to_object(replies[i]);
} }
} }
if (typeof args[args.length - 1] === "function") { if (typeof args[args.length - 1] === 'function') {
if (replies[i] instanceof Error) { if (replies[i] instanceof Error) {
args[args.length - 1](replies[i]); args[args.length - 1](replies[i]);
} else { } else {
@@ -1087,11 +1090,7 @@ Multi.prototype.execute_callback = function (err, replies) {
} }
}; };
RedisClient.prototype.multi = RedisClient.prototype.MULTI = function (args) { var createClient_unix = function (path, options){
return new Multi(this, args);
};
var createClient_unix = function(path, options){
var cnxOptions = { var cnxOptions = {
path: path path: path
}; };
@@ -1106,9 +1105,9 @@ var createClient_unix = function(path, options){
var createClient_tcp = function (port_arg, host_arg, options) { var createClient_tcp = function (port_arg, host_arg, options) {
var cnxOptions = { var cnxOptions = {
'port' : port_arg || default_port, port : port_arg || default_port,
'host' : host_arg || default_host, host : host_arg || default_host,
'family' : options && options.family === 'IPv6' ? 6 : 4 family : options && options.family === 'IPv6' ? 6 : 4
}; };
var net_client = net.createConnection(cnxOptions); var net_client = net.createConnection(cnxOptions);
var redis_client = new RedisClient(net_client, options); var redis_client = new RedisClient(net_client, options);
@@ -1119,7 +1118,7 @@ var createClient_tcp = function (port_arg, host_arg, options) {
return redis_client; return redis_client;
}; };
exports.createClient = function(port_arg, host_arg, options) { var createClient = function (port_arg, host_arg, options) {
if (typeof port_arg === 'object' || port_arg === undefined) { if (typeof port_arg === 'object' || port_arg === undefined) {
options = port_arg || options || {}; options = port_arg || options || {};
return createClient_tcp(+options.port, options.host, options); return createClient_tcp(+options.port, options.host, options);
@@ -1143,5 +1142,7 @@ exports.createClient = function(port_arg, host_arg, options) {
throw new Error('Unknown type of connection in createClient()'); throw new Error('Unknown type of connection in createClient()');
}; };
exports.createClient = createClient;
exports.RedisClient = RedisClient;
exports.print = utils.print; exports.print = utils.print;
exports.Multi = Multi; exports.Multi = Multi;

View File

@@ -1,6 +1,6 @@
'use strict'; 'use strict';
var hiredis = require("hiredis"); var hiredis = require('hiredis');
function HiredisReplyParser(return_buffers) { function HiredisReplyParser(return_buffers) {
this.name = exports.name; this.name = exports.name;
@@ -39,4 +39,4 @@ HiredisReplyParser.prototype.execute = function (data) {
}; };
exports.Parser = HiredisReplyParser; exports.Parser = HiredisReplyParser;
exports.name = "hiredis"; exports.name = 'hiredis';

View File

@@ -1,6 +1,6 @@
'use strict'; 'use strict';
var util = require("util"); var util = require('util');
function Packet(type, size) { function Packet(type, size) {
this.type = type; this.type = type;
@@ -13,11 +13,11 @@ function ReplyParser(return_buffers) {
this._buffer = new Buffer(0); this._buffer = new Buffer(0);
this._offset = 0; this._offset = 0;
this._encoding = "utf-8"; this._encoding = 'utf-8';
} }
function IncompleteReadBuffer(message) { function IncompleteReadBuffer(message) {
this.name = "IncompleteReadBuffer"; this.name = 'IncompleteReadBuffer';
this.message = message; this.message = message;
} }
util.inherits(IncompleteReadBuffer, Error); util.inherits(IncompleteReadBuffer, Error);
@@ -31,7 +31,7 @@ ReplyParser.prototype._parseResult = function (type) {
start = this._offset; start = this._offset;
if (end > this._buffer.length) { if (end > this._buffer.length) {
throw new IncompleteReadBuffer("Wait for more data."); throw new IncompleteReadBuffer('Wait for more data.');
} }
// include the delimiter // include the delimiter
@@ -49,7 +49,7 @@ ReplyParser.prototype._parseResult = function (type) {
start = this._offset; start = this._offset;
if (end > this._buffer.length) { if (end > this._buffer.length) {
throw new IncompleteReadBuffer("Wait for more data."); throw new IncompleteReadBuffer('Wait for more data.');
} }
// include the delimiter // include the delimiter
@@ -73,7 +73,7 @@ ReplyParser.prototype._parseResult = function (type) {
start = this._offset; start = this._offset;
if (end > this._buffer.length) { if (end > this._buffer.length) {
throw new IncompleteReadBuffer("Wait for more data."); throw new IncompleteReadBuffer('Wait for more data.');
} }
// set the offset to after the delimiter // set the offset to after the delimiter
@@ -93,7 +93,7 @@ ReplyParser.prototype._parseResult = function (type) {
if (packetHeader.size > this._bytesRemaining()) { if (packetHeader.size > this._bytesRemaining()) {
this._offset = offset - 1; this._offset = offset - 1;
throw new IncompleteReadBuffer("Wait for more data."); throw new IncompleteReadBuffer('Wait for more data.');
} }
var reply = []; var reply = [];
@@ -105,7 +105,7 @@ ReplyParser.prototype._parseResult = function (type) {
ntype = this._buffer[this._offset++]; ntype = this._buffer[this._offset++];
if (this._offset > this._buffer.length) { if (this._offset > this._buffer.length) {
throw new IncompleteReadBuffer("Wait for more data."); throw new IncompleteReadBuffer('Wait for more data.');
} }
res = this._parseResult(ntype); res = this._parseResult(ntype);
reply.push(res); reply.push(res);
@@ -199,7 +199,7 @@ ReplyParser.prototype._packetEndOffset = function () {
/* istanbul ignore if: activate the js parser out of memory test to test this */ /* istanbul ignore if: activate the js parser out of memory test to test this */
if (offset >= this._buffer.length) { if (offset >= this._buffer.length) {
throw new IncompleteReadBuffer("didn't see LF after NL reading multi bulk count (" + offset + " => " + this._buffer.length + ", " + this._offset + ")"); throw new IncompleteReadBuffer('Did not see LF after NL reading multi bulk count (' + offset + ' => ' + this._buffer.length + ', ' + this._offset + ')');
} }
} }
@@ -212,4 +212,4 @@ ReplyParser.prototype._bytesRemaining = function () {
}; };
exports.Parser = ReplyParser; exports.Parser = ReplyParser;
exports.name = "javascript"; exports.name = 'javascript';

View File

@@ -52,7 +52,7 @@ Queue.prototype.getLength = function () {
return this.head.length - this.offset + this.tail.length; return this.head.length - this.offset + this.tail.length;
}; };
Object.defineProperty(Queue.prototype, "length", { Object.defineProperty(Queue.prototype, 'length', {
get: function () { get: function () {
return this.getLength(); return this.getLength();
} }

View File

@@ -48,9 +48,9 @@ function toArray(args) {
function print (err, reply) { function print (err, reply) {
if (err) { if (err) {
console.log("Error: " + err); console.log('Error: ' + err);
} else { } else {
console.log("Reply: " + reply); console.log('Reply: ' + reply);
} }
} }