Browse Source

Small style changes

greenkeeper-update-all
Ruben Bridgewater 9 years ago
parent
commit
7922d4eb85
  1. 8
      README.md
  2. 26
      benchmarks/buffer_bench.js
  3. 2
      benchmarks/diff_multi_bench_output.js
  4. 98
      benchmarks/multi_bench.js
  5. 2
      changelog.md
  6. 6
      examples/auth.js
  7. 14
      examples/backpressure_drain.js
  8. 6
      examples/eval.js
  9. 6
      examples/extend.js
  10. 16
      examples/file.js
  11. 4
      examples/mget.js
  12. 10
      examples/monitor.js
  13. 26
      examples/multi.js
  14. 14
      examples/multi2.js
  15. 22
      examples/psubscribe.js
  16. 30
      examples/pub_sub.js
  17. 29
      examples/scan.js
  18. 22
      examples/simple.js
  19. 22
      examples/sort.js
  20. 8
      examples/subqueries.js
  21. 10
      examples/subquery.js
  22. 18
      examples/unix_socket.js
  23. 22
      examples/web_server.js
  24. 323
      index.js
  25. 4
      lib/parsers/hiredis.js
  26. 20
      lib/parsers/javascript.js
  27. 2
      lib/queue.js
  28. 4
      lib/utils.js

8
README.md

@ -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.
* `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.
* `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.
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.
* `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.
* `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.
* `disable_resubscribing`: *false*; If set to `true`, a client won't resubscribe after disconnecting
```js

26
benchmarks/buffer_bench.js

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

2
benchmarks/diff_multi_bench_output.js

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

98
benchmarks/multi_bench.js

@ -1,11 +1,11 @@
'use strict';
var path = require('path');
var RedisProcess = require("../test/lib/redis-process");
var RedisProcess = require('../test/lib/redis-process');
var rp;
var redis = require("../index");
var redis = require('../index');
var totalTime = 0;
var metrics = require("metrics");
var metrics = require('metrics');
var num_clients = parseInt(process.argv[2], 10) || 5;
var num_requests = 50000;
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) {
var str = input.toString();
chr = chr || " ";
chr = chr || ' ';
while (str.length < len) {
str = chr + str;
@ -30,7 +30,7 @@ function lpad(input, len, chr) {
metrics.Histogram.prototype.print_line = function () {
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) {
@ -66,14 +66,14 @@ Test.prototype.new_client = function (id) {
new_client = redis.createClient(this.client_options);
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);
});
new_client.on("ready", function () {
new_client.on('ready', function () {
if (! versions_logged) {
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);
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);
versions_logged = true;
}
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
new_client.on("error", function(err) {
new_client.on('error', function(err) {
if (err.code === 'CONNECTION_BROKEN') {
throw err;
}
@ -105,7 +105,7 @@ Test.prototype.new_client = function (id) {
};
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.fill_pipeline();
@ -159,64 +159,64 @@ Test.prototype.print_stats = function () {
var duration = Date.now() - this.test_start;
totalTime += duration;
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");
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');
};
small_str = "1234";
small_str = '1234';
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);
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);
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: 1}));
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: 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: 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: 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: 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: 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: 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: 50, 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: "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: 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 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: 1}));
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: 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: 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: 50, 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: "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: 1}));
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: 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: 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: 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: 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: 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: 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: 50, 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: "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: 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 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: 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} }));
function next() {
var test = tests.shift();
@ -231,7 +231,7 @@ function next() {
next();
});
} else {
console.log("End of tests. Total time elapsed:", totalTime, 'ms');
console.log('End of tests. Total time elapsed:', totalTime, 'ms');
process.exit(0);
}
}

2
changelog.md

@ -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)
- 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)
- 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 .auth calling the callback twice if already connected (@BridgeAR)
- Fix detect_buffers not working in pub sub mode and while monitoring (@BridgeAR)

6
examples/auth.js

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

14
examples/backpressure_drain.js

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

6
examples/eval.js

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

6
examples/extend.js

@ -1,14 +1,14 @@
'use strict';
var redis = require("redis"),
var redis = require('redis'),
client = redis.createClient();
// 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) {
this.info(function (err, res) {
var lines = res.toString().split("\r\n").sort();
var lines = res.toString().split('\r\n').sort();
var obj = {};
lines.forEach(function (line) {
var parts = line.split(':');

16
examples/file.js

@ -2,10 +2,10 @@
// 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(),
fs = require("fs"),
filename = "kids_in_cart.jpg";
fs = require('fs'),
filename = 'kids_in_cart.jpg';
// Get the file I use for testing like this:
// 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.
fs.readFile(filename, function (err, data) {
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.get(filename, function (err, reply) { // get entire file
if (err) {
console.log("Get error: " + err);
console.log('Get error: ' + err);
} else {
fs.writeFile("duplicate_" + filename, reply, function (err) {
fs.writeFile('duplicate_' + filename, reply, function (err) {
if (err) {
console.log("Error on write: " + err);
console.log('Error on write: ' + err);
} else {
console.log("File written.");
console.log('File written.');
}
client.end();
});

4
examples/mget.js

@ -1,7 +1,7 @@
'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);
});

10
examples/monitor.js

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

26
examples/multi.js

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

14
examples/multi2.js

@ -1,15 +1,15 @@
'use strict';
var redis = require("redis"),
var redis = require('redis'),
client = redis.createClient(), multi;
// start a separate command queue for multi
multi = client.multi();
multi.incr("incr thing", redis.print);
multi.incr("incr other thing", redis.print);
multi.incr('incr thing', redis.print);
multi.incr('incr other thing', redis.print);
// 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
multi.exec(function (err, replies) {
@ -23,9 +23,9 @@ multi.exec(function (err, replies) {
});
client.multi([
["mget", "multifoo", "multibar", redis.print],
["incr", "multifoo"],
["incr", "multibar"]
['mget', 'multifoo', 'multibar', redis.print],
['incr', 'multifoo'],
['incr', 'multibar']
]).exec(function (err, replies) {
console.log(replies.toString());
});

22
examples/psubscribe.js

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

30
examples/pub_sub.js

@ -1,41 +1,41 @@
'use strict';
var redis = require("redis"),
var redis = require('redis'),
client1 = redis.createClient(), msg_count = 0,
client2 = redis.createClient();
// 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) {
console.log("client1 subscribed to " + channel + ", " + count + " total subscriptions");
// 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) {
console.log('client1 subscribed to ' + channel + ', ' + count + ' total subscriptions');
if (count === 2) {
client2.publish("a nice channel", "I am sending a 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 a message.');
client2.publish('another one', 'I am sending a second message.');
client2.publish('a nice channel', 'I am sending my last message.');
}
});
client1.on("unsubscribe", function (channel, count) {
console.log("client1 unsubscribed from " + channel + ", " + count + " total subscriptions");
client1.on('unsubscribe', function (channel, count) {
console.log('client1 unsubscribed from ' + channel + ', ' + count + ' total subscriptions');
if (count === 0) {
client2.end();
client1.end();
}
});
client1.on("message", function (channel, message) {
console.log("client1 channel " + channel + ": " + message);
client1.on('message', function (channel, message) {
console.log('client1 channel ' + channel + ': ' + message);
msg_count += 1;
if (msg_count === 3) {
client1.unsubscribe();
}
});
client1.on("ready", function () {
client1.on('ready', function () {
// if you need auth, do it here
client1.incr("did a thing");
client1.subscribe("a nice channel", "another one");
client1.incr('did a thing');
client1.subscribe('a nice channel', 'another one');
});
client2.on("ready", function () {
client2.on('ready', function () {
// if you need auth, do it here
});

29
examples/scan.js

@ -1,6 +1,6 @@
'use strict';
var redis = require("redis"),
var redis = require('redis'),
client = redis.createClient();
var cursor = '0';
@ -8,8 +8,8 @@ var cursor = '0';
function scan() {
client.scan(
cursor,
"MATCH", "q:job:*",
"COUNT", "10",
'MATCH', 'q:job:*',
'COUNT', '10',
function(err, res) {
if (err) throw err;
@ -17,22 +17,21 @@ function scan() {
cursor = res[0];
// From <http://redis.io/commands/scan>:
// "An iteration starts when the cursor is set to 0,
// and terminates when the cursor returned by the server is 0."
// 'An iteration starts when the cursor is set to 0,
// and terminates when the cursor returned by the server is 0.'
if (cursor === '0') {
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]);
}
}
// 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
return scan();
if (res[1].length > 0) {
console.log('Array of matching keys', res[1]);
}
return scan();
}
);
}

22
examples/simple.js

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

22
examples/sort.js

@ -1,19 +1,19 @@
'use strict';
var redis = require("redis"),
var redis = require('redis'),
client = redis.createClient();
client.sadd("mylist", 1);
client.sadd("mylist", 2);
client.sadd("mylist", 3);
client.sadd('mylist', 1);
client.sadd('mylist', 2);
client.sadd('mylist', 3);
client.set("weight_1", 5);
client.set("weight_2", 500);
client.set("weight_3", 1);
client.set('weight_1', 5);
client.set('weight_2', 500);
client.set('weight_3', 1);
client.set("object_1", "foo");
client.set("object_2", "bar");
client.set("object_3", "qux");
client.set('object_1', 'foo');
client.set('object_2', 'bar');
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

8
examples/subqueries.js

@ -1,14 +1,14 @@
'use strict';
// 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) {
client.type(key, function (err, keytype) {
console.log(key + " is " + keytype);
console.log(key + ' is ' + keytype);
if (pos === (keys.length - 1)) {
client.quit();
}

10
examples/subquery.js

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

18
examples/unix_socket.js

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

22
examples/web_server.js

@ -2,12 +2,12 @@
// A simple web server that generates dyanmic content based on responses from Redis
var http = require("http"), server,
redis_client = require("redis").createClient();
var http = require('http'), server,
redis_client = require('redis').createClient();
server = http.createServer(function (request, response) {
response.writeHead(200, {
"Content-Type": "text/plain"
'Content-Type': 'text/plain'
});
var redis_info, total_requests;
@ -15,18 +15,18 @@ server = http.createServer(function (request, response) {
redis_client.info(function (err, reply) {
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
});
redis_client.hincrby("ip", request.connection.remoteAddress, 1);
redis_client.hgetall("ip", function (err, reply) {
redis_client.hincrby('ip', request.connection.remoteAddress, 1);
redis_client.hgetall('ip', function (err, reply) {
// 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" +
"Redis info:\n" + redis_info + "\n" +
"Total requests: " + total_requests + "\n\n" +
"IP count: \n");
response.write('This page was generated after talking to redis.\n\n' +
'Redis info:\n' + redis_info + '\n' +
'Total requests: ' + total_requests + '\n\n' +
'IP count: \n');
Object.keys(reply).forEach(function (ip) {
response.write(" " + ip + ": " + reply[ip] + "\n");
response.write(' ' + ip + ': ' + reply[ip] + '\n');
});
response.end();
});

323
index.js

@ -1,36 +1,36 @@
'use strict';
var net = require("net"),
URL = require("url"),
util = require("util"),
utils = require("./lib/utils"),
Queue = require("./lib/queue"),
Command = require("./lib/command"),
events = require("events"),
parsers = [],
// This static list of commands is updated from time to time.
// ./lib/commands.js can be updated with generate_commands.js
commands = require("./lib/commands"),
connection_id = 0,
default_port = 6379,
default_host = "127.0.0.1",
debug = function(msg) {
if (exports.debug_mode) {
console.error(msg);
}
};
var net = require('net');
var URL = require('url');
var util = require('util');
var utils = require('./lib/utils');
var Queue = require('./lib/queue');
var Command = require('./lib/command');
var events = require('events');
var parsers = [];
// This static list of commands is updated from time to time.
// ./lib/commands.js can be updated with generate_commands.js
var commands = require('./lib/commands');
var connection_id = 0;
var default_port = 6379;
var default_host = '127.0.0.1';
var debug = function(msg) {
if (exports.debug_mode) {
console.error(msg);
}
};
exports.debug_mode = /\bredis\b/i.test(process.env.NODE_DEBUG);
// hiredis might not be installed
try {
parsers.push(require("./lib/parsers/hiredis"));
parsers.push(require('./lib/parsers/hiredis'));
} catch (err) {
/* 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) {
options = options || {};
@ -76,36 +76,35 @@ function RedisClient(stream, options) {
events.EventEmitter.call(this);
}
util.inherits(RedisClient, events.EventEmitter);
exports.RedisClient = RedisClient;
RedisClient.prototype.install_stream_listeners = function() {
var self = this;
this.stream.on("connect", function () {
this.stream.on('connect', function () {
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
// 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);
});
this.stream.on("error", function (err) {
this.stream.on('error', function (err) {
self.on_error(err);
});
this.stream.on("close", function () {
self.connection_gone("close");
this.stream.on('close', function () {
self.connection_gone('close');
});
this.stream.on("end", function () {
self.connection_gone("end");
this.stream.on('end', function () {
self.connection_gone('end');
});
this.stream.on("drain", function () {
this.stream.on('drain', function () {
self.should_buffer = false;
self.emit("drain");
self.emit('drain');
});
};
@ -122,8 +121,8 @@ RedisClient.prototype.unref = function () {
debug("Unref'ing the socket connection");
this.stream.unref();
} else {
debug("Not connected yet, will unref later");
this.once("connect", function () {
debug('Not connected yet, will unref later');
this.once('connect', function () {
this.unref();
});
}
@ -134,7 +133,7 @@ RedisClient.prototype.flush_and_error = function (error) {
var command_obj;
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();
command_obj.callback(error);
}
@ -142,7 +141,7 @@ RedisClient.prototype.flush_and_error = function (error) {
this.offline_queue = new Queue();
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();
command_obj.callback(error);
}
@ -155,16 +154,16 @@ RedisClient.prototype.on_error = function (err) {
return;
}
err.message = "Redis connection to " + this.address + " failed - " + err.message;
err.message = 'Redis connection to ' + this.address + ' failed - ' + err.message;
debug(err.message);
this.connected = false;
this.ready = false;
this.emit("error", err);
// "error" events get turned into exceptions if they aren't listened for. If the user handled this error
this.emit('error', err);
// 'error' events get turned into exceptions if they aren't listened for. If the user handled this error
// then we should try to reconnect.
this.connection_gone("error");
this.connection_gone('error');
};
var noPasswordIsSet = /no password is set/;
@ -173,35 +172,35 @@ var loading = /LOADING/;
RedisClient.prototype.do_auth = function () {
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_command("auth", [this.auth_pass], function (err, res) {
self.send_command('auth', [this.auth_pass], function (err, res) {
if (err) {
/* istanbul ignore if: this is almost impossible to test */
if (loading.test(err.message)) {
// 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 () {
self.do_auth();
}, 333);
return;
} 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;
res = "OK";
res = 'OK';
} else if (self.auth_callback) {
self.auth_callback(err);
self.auth_callback = null;
return;
} else {
self.emit("error", err);
self.emit('error', err);
return;
}
}
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) {
self.auth_callback(null, res);
@ -209,7 +208,7 @@ RedisClient.prototype.do_auth = function () {
}
// Now we are really connected
self.emit("connect");
self.emit('connect');
self.initialize_retry_vars();
if (self.options.no_ready_check) {
@ -222,7 +221,7 @@ RedisClient.prototype.do_auth = 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.ready = false;
@ -240,7 +239,7 @@ RedisClient.prototype.on_connect = function () {
if (typeof this.auth_pass === 'string') {
this.do_auth();
} else {
this.emit("connect");
this.emit('connect');
this.initialize_retry_vars();
if (this.options.no_ready_check) {
@ -258,7 +257,7 @@ RedisClient.prototype.init_parser = function () {
if (!parsers.some(function (parser) {
if (parser.name === self.options.parser) {
self.parser_module = parser;
debug("Using parser module: " + self.parser_module.name);
debug('Using parser module: ' + self.parser_module.name);
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");
}
} else {
debug("Using default parser module: " + parsers[0].name);
debug('Using default parser module: ' + parsers[0].name);
this.parser_module = parsers[0];
}
@ -310,39 +309,39 @@ RedisClient.prototype.on_ready = function () {
this.pub_sub_mode = pub_sub_mode;
}
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 = function () {
callback_count--;
if (callback_count === 0) {
self.emit("ready");
self.emit('ready');
}
};
if (this.options.disable_resubscribing) {
return;
}
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)];
debug("Sending pub/sub on_ready " + parts[0] + ", " + parts[1]);
debug('Sending pub/sub on_ready ' + parts[0] + ', ' + parts[1]);
callback_count++;
self.send_command(parts[0] + "scribe", [parts[1]], callback);
self.send_command(parts[0] + 'scribe', [parts[1]], callback);
});
return;
}
if (this.monitoring) {
this.send_command("monitor", []);
this.send_command('monitor', []);
} else {
this.send_offline_queue();
}
this.emit("ready");
this.emit('ready');
};
RedisClient.prototype.on_info_cmd = function (err, res) {
if (err) {
err.message = "Ready check failed: " + err.message;
this.emit("error", err);
err.message = 'Ready check failed: ' + err.message;
this.emit('error', err);
return;
}
@ -356,7 +355,7 @@ RedisClient.prototype.on_info_cmd = function (err, res) {
var self = this;
var obj = {};
var lines = res.toString().split("\r\n");
var lines = res.toString().split('\r\n');
var i = 0;
var key = 'db' + i;
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
this.server_info = obj;
if (!obj.loading || obj.loading === "0") {
debug("Redis server ready.");
if (!obj.loading || obj.loading === '0') {
debug('Redis server ready.');
this.on_ready();
} else {
retry_time = obj.loading_eta_seconds * 1000;
if (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 () {
self.ready_check();
}, retry_time);
@ -408,9 +407,9 @@ RedisClient.prototype.on_info_cmd = function (err, res) {
RedisClient.prototype.ready_check = function () {
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) {
self.on_info_cmd(err, res);
});
@ -421,7 +420,7 @@ RedisClient.prototype.send_offline_queue = function () {
var command_obj, buffered_writes = 0;
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);
}
this.offline_queue = new Queue();
@ -429,14 +428,14 @@ RedisClient.prototype.send_offline_queue = function () {
if (!buffered_writes) {
this.should_buffer = false;
this.emit("drain");
this.emit('drain');
}
};
var retry_connection = function (self) {
debug("Retrying connection...");
debug('Retrying connection...');
self.emit("reconnecting", {
self.emit('reconnecting', {
delay: self.retry_delay,
attempt: self.attempts
});
@ -457,7 +456,7 @@ RedisClient.prototype.connection_gone = function (why) {
return;
}
debug("Redis connection is gone from " + why + " event.");
debug('Redis connection is gone from ' + why + ' event.');
this.connected = 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
if (!this.emitted_end) {
this.emit("end");
this.emit('end');
this.emitted_end = true;
}
// If this is a requested shutdown, then don't retry
if (this.closing) {
debug("Connection ended from quit command, not retrying.");
this.flush_and_error(new Error("Redis connection gone from " + why + " event."));
debug('Connection ended from quit command, not retrying.');
this.flush_and_error(new Error('Redis connection gone from ' + why + ' event.'));
return;
}
@ -490,7 +489,7 @@ RedisClient.prototype.connection_gone = function (why) {
var message = this.retry_totaltime >= this.connect_timeout ?
'connection timeout 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';
this.flush_and_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) {
this.command_queue = new Queue();
this.emit("idle");
this.emit('idle');
}
if (this.should_buffer && queue_len <= this.command_queue_low_water) {
this.emit("drain");
this.emit('drain');
this.should_buffer = false;
}
@ -545,7 +544,7 @@ RedisClient.prototype.return_error = function (err) {
RedisClient.prototype.return_reply = function (reply) {
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
// the head command prematurely.
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')) {
debug("Received pubsub message");
debug('Received pubsub message');
} else {
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) {
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) {
this.emit("drain");
this.emit('drain');
this.should_buffer = false;
}
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 (this.options.detect_buffers && command_obj.buffer_args === false) {
// 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);
} else {
debug("No callback for reply");
debug('No callback for reply');
}
} else if (this.pub_sub_mode || command_obj && command_obj.sub_command) {
if (Array.isArray(reply)) {
@ -595,29 +594,29 @@ RedisClient.prototype.return_reply = function (reply) {
}
type = reply[0].toString();
if (type === "message") {
this.emit("message", reply[1], reply[2]); // channel, message
} else if (type === "pmessage") {
this.emit("pmessage", reply[1], reply[2], reply[3]); // pattern, channel, message
} else if (type === "subscribe" || type === "unsubscribe" || type === "psubscribe" || type === "punsubscribe") {
if (type === 'message') {
this.emit('message', reply[1], reply[2]); // channel, message
} else if (type === 'pmessage') {
this.emit('pmessage', reply[1], reply[2], reply[3]); // pattern, channel, message
} else if (type === 'subscribe' || type === 'unsubscribe' || type === 'psubscribe' || type === 'punsubscribe') {
if (reply[2] === 0) {
this.pub_sub_mode = false;
debug("All subscriptions removed, exiting pub/sub mode");
debug('All subscriptions removed, exiting pub/sub mode');
} else {
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
// 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]);
}
this.emit(type, reply[1], reply[2]); // channel, count
} 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;
}
} 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;
}
}
@ -627,29 +626,29 @@ RedisClient.prototype.return_reply = function (reply) {
reply = reply.toString();
}
// 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);
argindex = reply.indexOf('"');
args = reply.slice(argindex + 1, -1).split('" "').map(function (elem) {
return elem.replace(/\\"/g, '"');
});
this.emit("monitor", timestamp, args);
this.emit('monitor', timestamp, args);
} 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;
this.emit("error", err);
this.emit('error', err);
}
};
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) {
args = [];
} else if (!callback) {
if (typeof args[args.length - 1] === "function") {
if (typeof args[args.length - 1] === 'function') {
callback = args.pop();
} else if (typeof args[args.length - 1] === "undefined") {
} else if (typeof args[args.length - 1] === 'undefined') {
args.pop();
}
}
@ -667,7 +666,7 @@ RedisClient.prototype.send_command = function (command, args, callback) {
if (callback) {
return callback && callback(err);
}
this.emit("error", err);
this.emit('error', err);
return;
}
}
@ -686,9 +685,9 @@ RedisClient.prototype.send_command = function (command, args, callback) {
if (this.closing || !this.enable_offline_queue) {
command = command.toUpperCase();
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 {
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;
if (callback) {
@ -697,23 +696,23 @@ RedisClient.prototype.send_command = function (command, args, callback) {
this.emit('error', err);
}
} else {
debug("Queueing " + command + " for next server connection.");
debug('Queueing ' + command + ' for next server connection.');
this.offline_queue.push(command_obj);
this.should_buffer = true;
}
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);
} else if (command === "monitor") {
} else if (command === 'monitor') {
this.monitoring = true;
} else if (command === "quit") {
} else if (command === 'quit') {
this.closing = 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();
this.emit("error", err);
this.emit('error', err);
return;
}
this.command_queue.push(command_obj);
@ -721,23 +720,23 @@ RedisClient.prototype.send_command = function (command, args, callback) {
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.
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
for (i = 0; i < args.length; i += 1) {
arg = args[i];
if (typeof arg !== "string") {
if (typeof arg !== 'string') {
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);
} else {
debug("Send command (" + command_str + ") has Buffer arguments");
debug('Send command (' + command_str + ') has Buffer arguments');
buffered_writes += !stream.write(command_str);
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 (arg.length === 0) {
debug("send_command: using empty string for 0 length buffer");
buffered_writes += !stream.write("$0\r\n\r\n");
debug('send_command: using empty string for 0 length buffer');
buffered_writes += !stream.write('$0\r\n\r\n');
} 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("\r\n");
debug("send_command: buffer send " + arg.length + " bytes");
buffered_writes += !stream.write('\r\n');
debug('send_command: buffer send ' + arg.length + ' bytes');
}
} else {
debug("send_command: string send " + Buffer.byteLength(arg) + " bytes: " + arg);
buffered_writes += !stream.write("$" + Buffer.byteLength(arg) + "\r\n" + arg + "\r\n");
debug('send_command: string send ' + Buffer.byteLength(arg) + ' bytes: ' + arg);
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) {
this.should_buffer = true;
}
@ -773,30 +772,30 @@ RedisClient.prototype.pub_sub_command = function (command_obj) {
var i, key, command, args;
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;
command_obj.sub_command = true;
command = command_obj.command;
args = command_obj.args;
if (command === "subscribe" || command === "psubscribe") {
if (command === "subscribe") {
key = "sub";
if (command === 'subscribe' || command === 'psubscribe') {
if (command === 'subscribe') {
key = 'sub';
} else {
key = "psub";
key = 'psub';
}
for (i = 0; i < args.length; i++) {
this.subscription_set[key + " " + args[i]] = true;
this.subscription_set[key + ' ' + args[i]] = true;
}
} else {
if (command === "unsubscribe") {
key = "sub";
if (command === 'unsubscribe') {
key = 'sub';
} else {
key = "psub";
key = 'psub';
}
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);
this.retry_timer = null;
}
this.stream.on("error", function noop(){});
this.stream.on('error', function noop(){});
// Flush queue if wanted
if (flush) {
@ -824,7 +823,7 @@ RedisClient.prototype.end = function (flush) {
function Multi(client, args) {
this._client = client;
this.queue = [["multi"]];
this.queue = [['multi']];
var command, tmp_args;
if (Array.isArray(args)) {
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) {
var command = fullCommand.split(' ')[0];
@ -923,10 +926,10 @@ RedisClient.prototype.auth = RedisClient.prototype.AUTH = function (pass, callba
return;
}
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
if (this.connected) {
this.send_command("auth", [this.auth_pass], callback);
this.send_command('auth', [this.auth_pass], callback);
} else {
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) {
var field, tmp_args;
if (Array.isArray(key)) {
return this.send_command("hmset", key, args);
return this.send_command('hmset', key, 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})
// assuming key is a string, i.e. email address
// 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
if (typeof key !== "string") {
if (typeof key !== 'string') {
key = key.toString();
}
tmp_args = [key];
@ -954,9 +957,9 @@ RedisClient.prototype.hmset = RedisClient.prototype.HMSET = function (key, args,
while (field = fields.shift()) {
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) {
@ -971,11 +974,11 @@ Multi.prototype.hmset = Multi.prototype.HMSET = function (key, args, callback) {
args = args.concat([callback]);
}
tmp_args = ['hmset', key].concat(args);
} else if (typeof args === "object") {
if (typeof key !== "string") {
} else if (typeof args === 'object') {
if (typeof key !== 'string') {
key = key.toString();
}
tmp_args = ["hmset", key];
tmp_args = ['hmset', key];
var fields = Object.keys(args);
while (field = fields.shift()) {
tmp_args.push(field);
@ -986,7 +989,7 @@ Multi.prototype.hmset = Multi.prototype.HMSET = function (key, args, callback) {
}
} else {
tmp_args = utils.to_array(arguments);
tmp_args.unshift("hmset");
tmp_args.unshift('hmset');
}
this.queue.push(tmp_args);
return this;
@ -1010,12 +1013,12 @@ Multi.prototype.exec = Multi.prototype.EXEC = function (callback) {
this.errors = [];
this.callback = callback;
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++) {
var args = this.queue[index].slice(0);
var command = args.shift();
var cb;
if (typeof args[args.length - 1] === "function") {
if (typeof args[args.length - 1] === 'function') {
cb = args.pop();
}
// 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) {
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
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) {
args[args.length - 1](replies[i]);
} else {
@ -1087,11 +1090,7 @@ Multi.prototype.execute_callback = function (err, replies) {
}
};
RedisClient.prototype.multi = RedisClient.prototype.MULTI = function (args) {
return new Multi(this, args);
};
var createClient_unix = function(path, options){
var createClient_unix = function (path, options){
var cnxOptions = {
path: path
};
@ -1106,9 +1105,9 @@ var createClient_unix = function(path, options){
var createClient_tcp = function (port_arg, host_arg, options) {
var cnxOptions = {
'port' : port_arg || default_port,
'host' : host_arg || default_host,
'family' : options && options.family === 'IPv6' ? 6 : 4
port : port_arg || default_port,
host : host_arg || default_host,
family : options && options.family === 'IPv6' ? 6 : 4
};
var net_client = net.createConnection(cnxOptions);
var redis_client = new RedisClient(net_client, options);
@ -1119,7 +1118,7 @@ var createClient_tcp = function (port_arg, host_arg, options) {
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) {
options = port_arg || 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()');
};
exports.createClient = createClient;
exports.RedisClient = RedisClient;
exports.print = utils.print;
exports.Multi = Multi;

4
lib/parsers/hiredis.js

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

20
lib/parsers/javascript.js

@ -1,6 +1,6 @@
'use strict';
var util = require("util");
var util = require('util');
function Packet(type, size) {
this.type = type;
@ -13,11 +13,11 @@ function ReplyParser(return_buffers) {
this._buffer = new Buffer(0);
this._offset = 0;
this._encoding = "utf-8";
this._encoding = 'utf-8';
}
function IncompleteReadBuffer(message) {
this.name = "IncompleteReadBuffer";
this.name = 'IncompleteReadBuffer';
this.message = message;
}
util.inherits(IncompleteReadBuffer, Error);
@ -31,7 +31,7 @@ ReplyParser.prototype._parseResult = function (type) {
start = this._offset;
if (end > this._buffer.length) {
throw new IncompleteReadBuffer("Wait for more data.");
throw new IncompleteReadBuffer('Wait for more data.');
}
// include the delimiter
@ -49,7 +49,7 @@ ReplyParser.prototype._parseResult = function (type) {
start = this._offset;
if (end > this._buffer.length) {
throw new IncompleteReadBuffer("Wait for more data.");
throw new IncompleteReadBuffer('Wait for more data.');
}
// include the delimiter
@ -73,7 +73,7 @@ ReplyParser.prototype._parseResult = function (type) {
start = this._offset;
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
@ -93,7 +93,7 @@ ReplyParser.prototype._parseResult = function (type) {
if (packetHeader.size > this._bytesRemaining()) {
this._offset = offset - 1;
throw new IncompleteReadBuffer("Wait for more data.");
throw new IncompleteReadBuffer('Wait for more data.');
}
var reply = [];
@ -105,7 +105,7 @@ ReplyParser.prototype._parseResult = function (type) {
ntype = this._buffer[this._offset++];
if (this._offset > this._buffer.length) {
throw new IncompleteReadBuffer("Wait for more data.");
throw new IncompleteReadBuffer('Wait for more data.');
}
res = this._parseResult(ntype);
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 */
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.name = "javascript";
exports.name = 'javascript';

2
lib/queue.js

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

4
lib/utils.js

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

Loading…
Cancel
Save