Giter VIP home page Giter VIP logo

node-redis's Introduction

Node-Redis

Tests Coverage License

Discord Twitch YouTube Twitter

node-redis is a modern, high performance Redis client for Node.js.

How do I Redis?

Learn for free at Redis University

Build faster with the Redis Launchpad

Try the Redis Cloud

Dive in developer tutorials

Join the Redis community

Work at Redis

Packages

Name Description
redis Downloads Version
@redis/client Downloads Version Docs
@redis/bloom Downloads Version Docs Redis Bloom commands
@redis/graph Downloads Version Docs Redis Graph commands
@redis/json Downloads Version Docs Redis JSON commands
@redis/search Downloads Version Docs RediSearch commands
@redis/time-series Downloads Version Docs Redis Time-Series commands

⚠️ In version 4.1.0 we moved our subpackages from @node-redis to @redis. If you're just using npm install redis, you don't need to do anything—it'll upgrade automatically. If you're using the subpackages directly, you'll need to point to the new scope (e.g. @redis/client instead of @node-redis/client).

Installation

Start a redis via docker:

docker run -p 6379:6379 -it redis/redis-stack-server:latest

To install node-redis, simply:

npm install redis

⚠️ The new interface is clean and cool, but if you have an existing codebase, you'll want to read the migration guide.

Looking for a high-level library to handle object mapping? See redis-om-node!

Usage

Basic Example

import { createClient } from 'redis';

const client = await createClient()
  .on('error', err => console.log('Redis Client Error', err))
  .connect();

await client.set('key', 'value');
const value = await client.get('key');
await client.disconnect();

The above code connects to localhost on port 6379. To connect to a different host or port, use a connection string in the format redis[s]://[[username][:password]@][host][:port][/db-number]:

createClient({
  url: 'redis://alice:[email protected]:6380'
});

You can also use discrete parameters, UNIX sockets, and even TLS to connect. Details can be found in the client configuration guide.

To check if the the client is connected and ready to send commands, use client.isReady which returns a boolean. client.isOpen is also available. This returns true when the client's underlying socket is open, and false when it isn't (for example when the client is still connecting or reconnecting after a network error).

Redis Commands

There is built-in support for all of the out-of-the-box Redis commands. They are exposed using the raw Redis command names (HSET, HGETALL, etc.) and a friendlier camel-cased version (hSet, hGetAll, etc.):

// raw Redis commands
await client.HSET('key', 'field', 'value');
await client.HGETALL('key');

// friendly JavaScript commands
await client.hSet('key', 'field', 'value');
await client.hGetAll('key');

Modifiers to commands are specified using a JavaScript object:

await client.set('key', 'value', {
  EX: 10,
  NX: true
});

Replies will be transformed into useful data structures:

await client.hGetAll('key'); // { field1: 'value1', field2: 'value2' }
await client.hVals('key'); // ['value1', 'value2']

Buffers are supported as well:

await client.hSet('key', 'field', Buffer.from('value')); // 'OK'
await client.hGetAll(
  commandOptions({ returnBuffers: true }),
  'key'
); // { field: <Buffer 76 61 6c 75 65> }

Unsupported Redis Commands

If you want to run commands and/or use arguments that Node Redis doesn't know about (yet!) use .sendCommand():

await client.sendCommand(['SET', 'key', 'value', 'NX']); // 'OK'

await client.sendCommand(['HGETALL', 'key']); // ['key1', 'field1', 'key2', 'field2']

Transactions (Multi/Exec)

Start a transaction by calling .multi(), then chaining your commands. When you're done, call .exec() and you'll get an array back with your results:

await client.set('another-key', 'another-value');

const [setKeyReply, otherKeyValue] = await client
  .multi()
  .set('key', 'value')
  .get('another-key')
  .exec(); // ['OK', 'another-value']

You can also watch keys by calling .watch(). Your transaction will abort if any of the watched keys change.

To dig deeper into transactions, check out the Isolated Execution Guide.

Blocking Commands

Any command can be run on a new connection by specifying the isolated option. The newly created connection is closed when the command's Promise is fulfilled.

This pattern works especially well for blocking commands—such as BLPOP and BLMOVE:

import { commandOptions } from 'redis';

const blPopPromise = client.blPop(
  commandOptions({ isolated: true }),
  'key',
  0
);

await client.lPush('key', ['1', '2']);

await blPopPromise; // '2'

To learn more about isolated execution, check out the guide.

Pub/Sub

See the Pub/Sub overview.

Scan Iterator

SCAN results can be looped over using async iterators:

for await (const key of client.scanIterator()) {
  // use the key!
  await client.get(key);
}

This works with HSCAN, SSCAN, and ZSCAN too:

for await (const { field, value } of client.hScanIterator('hash')) {}
for await (const member of client.sScanIterator('set')) {}
for await (const { score, value } of client.zScanIterator('sorted-set')) {}

You can override the default options by providing a configuration object:

client.scanIterator({
  TYPE: 'string', // `SCAN` only
  MATCH: 'patter*',
  COUNT: 100
});

Redis provides a programming interface allowing code execution on the redis server.

The following example retrieves a key in redis, returning the value of the key, incremented by an integer. For example, if your key foo has the value 17 and we run add('foo', 25), it returns the answer to Life, the Universe and Everything.

#!lua name=library

redis.register_function {
  function_name = 'add',
  callback = function(keys, args) return redis.call('GET', keys[1]) + args[1] end,
  flags = { 'no-writes' }
}

Here is the same example, but in a format that can be pasted into the redis-cli.

FUNCTION LOAD "#!lua name=library\nredis.register_function{function_name=\"add\", callback=function(keys, args) return redis.call('GET', keys[1])+args[1] end, flags={\"no-writes\"}}"

Load the prior redis function on the redis server before running the example below.

import { createClient } from 'redis';

const client = createClient({
  functions: {
    library: {
      add: {
        NUMBER_OF_KEYS: 1,
        transformArguments(key: string, toAdd: number): Array<string> {
          return [key, toAdd.toString()];
        },
        transformReply(reply: number): number {
          return reply;
        }
      }
    }
  }
});

await client.connect();

await client.set('key', '1');
await client.library.add('key', 2); // 3

The following is an end-to-end example of the prior concept.

import { createClient, defineScript } from 'redis';

const client = createClient({
  scripts: {
    add: defineScript({
      NUMBER_OF_KEYS: 1,
      SCRIPT:
        'return redis.call("GET", KEYS[1]) + ARGV[1];',
      transformArguments(key: string, toAdd: number): Array<string> {
        return [key, toAdd.toString()];
      },
      transformReply(reply: number): number {
        return reply;
      }
    })
  }
});

await client.connect();

await client.set('key', '1');
await client.add('key', 2); // 3

Disconnecting

There are two functions that disconnect a client from the Redis server. In most scenarios you should use .quit() to ensure that pending commands are sent to Redis before closing a connection.

.QUIT()/.quit()

Gracefully close a client's connection to Redis, by sending the QUIT command to the server. Before quitting, the client executes any remaining commands in its queue, and will receive replies from Redis for each of them.

const [ping, get, quit] = await Promise.all([
  client.ping(),
  client.get('key'),
  client.quit()
]); // ['PONG', null, 'OK']

try {
  await client.get('key');
} catch (err) {
  // ClosedClient Error
}

.disconnect()

Forcibly close a client's connection to Redis immediately. Calling disconnect will not send further pending commands to the Redis server, or wait for or parse outstanding responses.

await client.disconnect();

Auto-Pipelining

Node Redis will automatically pipeline requests that are made during the same "tick".

client.set('Tm9kZSBSZWRpcw==', 'users:1');
client.sAdd('users:1:tokens', 'Tm9kZSBSZWRpcw==');

Of course, if you don't do something with your Promises you're certain to get unhandled Promise exceptions. To take advantage of auto-pipelining and handle your Promises, use Promise.all().

await Promise.all([
  client.set('Tm9kZSBSZWRpcw==', 'users:1'),
  client.sAdd('users:1:tokens', 'Tm9kZSBSZWRpcw==')
]);

Clustering

Check out the Clustering Guide when using Node Redis to connect to a Redis Cluster.

Events

The Node Redis client class is an Nodejs EventEmitter and it emits an event each time the network status changes:

Name When Listener arguments
connect Initiating a connection to the server No arguments
ready Client is ready to use No arguments
end Connection has been closed (via .quit() or .disconnect()) No arguments
error An error has occurred—usually a network issue such as "Socket closed unexpectedly" (error: Error)
reconnecting Client is trying to reconnect to the server No arguments
sharded-channel-moved See here See here

⚠️ You MUST listen to error events. If a client doesn't have at least one error listener registered and an error occurs, that error will be thrown and the Node.js process will exit. See the EventEmitter docs for more details.

The client will not emit any other events beyond those listed above.

Supported Redis versions

Node Redis is supported with the following versions of Redis:

Version Supported
7.0.z ✔️
6.2.z ✔️
6.0.z ✔️
5.0.z ✔️
< 5.0

Node Redis should work with older versions of Redis, but it is not fully tested and we cannot offer support.

Contributing

If you'd like to contribute, check out the contributing guide.

Thank you to all the people who already contributed to Node Redis!

Contributors

License

This repository is licensed under the "MIT" license. See LICENSE.

node-redis's People

Contributors

andy-ganchrow avatar avital-fine avatar avitalfineredis avatar bcoe avatar bobrik avatar bridgear avatar brycebaril avatar chayim avatar dependabot[bot] avatar dtrejo avatar dvv avatar erinishimoticha avatar gkorland avatar greenkeeperio-bot avatar jerrysievert avatar leibale avatar migounette avatar mranney avatar paddybyers avatar pietern avatar ralexstokes avatar raydog avatar roamm avatar salakar avatar shin- avatar stockholmux avatar thanpolas avatar tim-smart avatar tj avatar tomaszdurka avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-redis's Issues

document pipelining

node_redis pipelines sort of automatically. This is quite a bit different than in other Redis client libraries, and it needs to be documented.

maybe a stupid question

hey, I'm new to redis (and node), so I apologize in advance if I'm simply doing something stupid.

I can save and get data in a node app just fine using your module. In particular I'm using hset and hget a lot. However, if I open a new terminal, type redis-cli and attempt to get any of the data that way, it's like the database is empty. I keep getting back "Invalid argument(s)". Any ideas why this would happen?

hmget fails when args.length > 1

var redis = require('redis')
  , client = redis.createClient();

client.hset('hash', 'key', 'val');

client.hmget('hash', ['key'], redis.print);
client.hmget('hash', 'key', 'key', redis.print);
client.hmget('hash', ['key', 'key'], redis.print);

client.quit();

/* output:
Reply: val
Reply: val,val
Reply: 
*/

Export the function that populates RedisClient.prototype

Please, export the function that populates RedisClient.prototype, so the user may add commands currently missing in node_redis at zero cost.

Also this would enable the user to "auto-update somehow" the interface in a sub-optimal fashion (e. g. downloading and parsing the commands.json) until there is a clear way to do it.

Thanks. :)

using node 0.3.0, tests fail right, left and center

The parsing of the response seems to have totally broken in node 0.3.0 -- I just get raw buffer objects back.
I'm using node 0.3.0, redis 2.0.4 and node_redis 0.3.8.
Btw: I tried this out, because redis-client also had the same problem, just shuffing buffers back.

Suggestion: use same function for both upper and lower case commands

In http://github.com/mranney/node_redis/blob/master/index.js#L696

This code:

exports.commands.forEach(function (command) {
    RedisClient.prototype[command] = function () {
        var args = to_array(arguments);
        args.unshift(command); // put command at the beginning
        this.send_command.apply(this, args);
    };
    // same as above, but command is lower case
    RedisClient.prototype[command.toLowerCase()] = function () {
        var args = to_array(arguments);
        args.unshift(command); // put command at the beginning
        this.send_command.apply(this, args);
    };
});

Could be reduced to the following code (with the added upside of using less memory, since the same function is shared for the two command names):

exports.commands.forEach(function (command) {
    RedisClient.prototype[command] = function () {
        var args = to_array(arguments);
        args.unshift(command); // put command at the beginning
        this.send_command.apply(this, args);
    };
    // same as above, but command is lower case
    RedisClient.prototype[command.toLowerCase()] = RedisClient.prototype[command];
});

Complains about HSET?

I tried to run the sample code you give, and I get:

sleet:persuasion davida$ node !$
node t.js
Reply: OK
Error: ERR unknown command 'HSET'
Error: ERR unknown command 'HSET'
Redis connection error to 127.0.0.1:6379 - TypeError: Cannot read property 'length' of undefined

(what's a bit weird is that I can do redis-cli hset ... w/ no problems).

Any ideas?

Returning wrong value

I think I managed to create race conditions where redis returns the wrong result for a query. Just trying to confirm my suspicion.

Is it possible for node_redis to confuse which result goes to which callback if I do stuff like this:

 redis.set('key1', 'something');
 redis.expire('key1', 100);
 redis.set('key2', 'something else');
 redis.set('key3', 'foo');
 redis.get('key1', function (err, data) { ... });
 redis.get('key2', function (err, data) {
     // what seems to be happening here is that after running for a while, it seems the wrong data starts getting returned
 });

MGET and empty array

Hey,

I know that original Redis syntax requires at least one key for MGET command, but since node_redis allows arrays, maybe it could allow an empty array as well? It could simply return an empty array without even sending command to Redis. It might be useful when doing nested calls to Redis and the command above can return an empty array.

Error: Redis reply parser error: TypeError: undefined is not a function

I'm trying to do a simple wrapper around node_redis. I have simple function like
exports.set = function(key,value,my_callback) {
client.set(key,value,function(err,reply) {
my_callback(reply.toString())
})}

but it fails with error in the title. I tracked that it has got something to do with parsing but unfortunately I'm not skilled enough to fix it myself and push the fix :( I have hiredis installed from npm.

Error: Redis reply parser error: TypeError: undefined is not a function
at CALL_NON_FUNCTION (native)
at Object.my_callback (/tmp/lib.js:15:2)
at Object.callback (/tmp/db/redis_wrapper.js:60:27)
at RedisClient.return_reply (/usr/local/lib/node/.npm/redis/0.4.1/package/index.js:259:25)
at HiredisReplyParser.<anonymous> (/usr/local/lib/node/.npm/redis/0.4.1/package/index.js:94:18)
at HiredisReplyParser.emit (events.js:31:17)
at HiredisReplyParser.execute (/usr/local/lib/node/.npm/redis/0.4.1/package/lib/parser/hiredis.js:35:22)
at RedisClient.on_data (/usr/local/lib/node/.npm/redis/0.4.1/package/index.js:216:27)
at Stream.<anonymous> (/usr/local/lib/node/.npm/redis/0.4.1/package/index.js:120:14)
at Stream.emit (events.js:31:17)

document reconnect scenarios

node_redis reconnects automatically when the connection fails, and often this does what you'd expect. There are some scenarios where unexpected things happen though, like if you have an outstanding blocking command like blpop, or if you are in subscribe mode. Further, sometimes on reconnect, you might notice that redis-server returns an error on all non-info commands, including subscribe.

changes binary data into javascript strings?

It seems like when I have binary data in redis and try to move that same data from one key to another using node_redis, it gets altered in the process. I'm not sure exactly where this happens.

I'm here at redis-cli:
redis> get "z"
"\x92\x95\xd0\x94\x01\x00\xd0\xc0\x0e\xcd\x02\x17"

Now I fire up node_redis and copy key "z" into key "x":
c = redis.createClient(null, 'localhost')
c.get('z', function(e, r) {c.set('x', r)})

Now I'm back at redis-cli:
redis> get "x"
"\xef\xbf\xbd\xef\xbf\xbd\xd0\x94\x01\x00\xef\xbf\xbd\xef\xbf\xbd\x0e\xef\xbf\xbd\x02\x17"

It seems like if I simply move data from one key to another key, it shouldn't get transformed in the process right?

Unrelated footnote: this bug appeared when we transitioned from fictorial's redis library to this one.

range passed as string should be passed as integer

For example this:
client.zrevrange('some-key', 0, -1)

produces this:

"zrevrange" "iMarionette:callQueue" "0" "-1"

but should produce this:

"zrevrange" "iMarionette:callQueue" 0 -1

and as a result I'm not able to get back any data using ranges.

No?

PSUBSCRIBE example

... if you want it. See this gist.

I thought you had a bug until I went and wrestled with the Redis docs for a while. But maybe that's not such a bad thing.

pass zunionstore array of keys

Is it possible to pass zunionstore an array for all of the keys that need to be unionized?

I have had no trouble with variables yet, and I can use an Array for multiple keys in mget(). I've been trying it here without success. eg:

var keys = ["mine", "yours"];
client.zunionstore("both", keys.length, keys, function(err, res){...})

Redis returns a syntax error apropos the keys.

multi + smembers

Not sure if you can reproduce this, but this query was hanging for me:

client.multi([
  ['smembers', ['some set'], fn],
  ['del', ['some set'], fn]
]);

Unknown error occurs after extended run time

Hey there. Getting this error on my production app after an extended run. Was wondering if you had any idea what it was. I'm new to node and from this stack trace am not sure where I could put a catch to catch the error so I can cleanly exit and restart the app.

Exception in RedisReplyParser: Error: end cannot be longer than parent.length
at Buffer.toString (buffer:39:19)
at RedisReplyParser.execute (/disk1/home/logplex/vendor/node_redis/index.js:91:52)
at RedisClient.on_data (/disk1/home/logplex/vendor/node_redis/index.js:429:27)
at Stream.<anonymous> (/disk1/home/logplex/vendor/node_redis/index.js:351:14)
at Stream.emit (events:26:26)
at IOWatcher.callback (net:489:16)
at node.js:764:9

node_redis and Step

I'm playing with Step and node_redis. However it seems for some reason my code gets stuck when I use client.get("foo",this). It just doesn't seem to return this correctly so Step can proceed to next function. Any ideas why this is happening?

Support for new bit commands

Current development version (2.2-RC2) of Redis supports four new commands related to bit manipulation. Please provide support for those commands. They are SETBIT, GETBIT, SETRANGE and GETRANGE.

Callback potentially called twice on multi.exec error

I haven't actually tried this but was reviewing the code to determine the callback sequence for multi execs. I think that you are missing a return on line 559 of index.js. The way it is coded, if send_command sends an err to this function, it will invoke the top-level callback once with the err and then again with (null, replies). You should change this line to:
return callback(new Error(err));

socket error randomly occuring with multi.exec

Hi I've got a problem with a socket error 'sometimes' occuring in my test suite. It only seems to occur during a multi-exec command I use. There's nothing interesting happening on the redis-server logs (i.e. it hasn't temporarily died).

Here's a back trace:

.......Redis connection error to 127.0.0.1:6379 - Error: Redis connection to 127.0.0.1:6379 failed - EPIPE, Broken pipe

   uncaught: Error: Socket is not writable
    at Socket._writeOut (net.js:370:11)
    at Socket.write (net.js:356:17)
    at RedisClient.send_command (/usr/local/lib/node/.npm/redis/0.5.7/package/index.js:513:16)
    at Multi.exec (/usr/local/lib/node/.npm/redis/0.5.7/package/index.js:684:17)
    at Function.loadFromIds (/Users/weepy/src/mmodel/lib/stores/redis.js:147:8)
    at Object.callback (/Users/weepy/src/mmodel/lib/stores/redis.js:132:13)
    at RedisClient.return_reply (/usr/local/lib/node/.npm/redis/0.5.7/package/index.js:385:29)
    at RedisReplyParser. (/usr/local/lib/node/.npm/redis/0.5.7/package/index.js:86:14)
    at RedisReplyParser.emit (events.js:42:17)
    at RedisReplyParser.add_multi_bulk_reply (/usr/local/lib/node/.npm/redis/0.5.7/package/lib/parser/javascript.js:297:14)


   Failures: 1


Q: about client.end() placement

Given the following express app route flow:

app.get('/', getSesh, function(req, res){
multi = client.multi();
client.zrevrangebyscore('frontPage', epoch(), epoch()-450061, "limit", "0", "75", function(err, data){
    if(err){console.log(err)}
    for (d in data)
    {
        multi.hgetall(data[d]){
        })
    }
    multi.exec(function(err, reply){
        if(err){console.log(err)}
        articles = reply;
        res.render('index', {
            locals: {title: "MOSTMODERNIST", articles: articles, admin: req.isAdmin}
        });
        res.end();
    }); 
});
});

Where / when should I put client.end()? I've experimented and gotten gnarly results. Previously I wasn't quitting them, letting redis disconnect them.

many tia

depend on hiredis

For portability, a pure JavaScript reply parser is used by default.

Is portability a real, or theoretical issue? If it's real, wouldn't adding platform support to hiredis be the open-source thing to do?

Everything is a buffer

Everything returned from keys, hkeys, etc is a Buffer.

For such simple types I have to wonder why...

Cannot read property 'length' of undefined

I'm not sure what's going on here, but I sometimes get this error:

Message: Redis connection to database:6379 failed - Cannot read property 'length' of undefined
Error: Redis connection to database:6379 failed - Cannot read property 'length' of undefined
at Stream.<anonymous> (/home/prod/.node_libraries/.npm/redis/0.5.0/package/index.js:140:28)
at Stream.emit (events:31:17)
at Array.<anonymous> (net:1004:27)
at EventEmitter._tickCallback (node.js:55:22)
at node.js:773:9

Is there something I can do to trace this deeper?

hgetall returns {} when no results

Testing for if(results) ends up with a false positive.
This could be an easy fix by setting the result to be null if no properties/keys have been set, but I'm just putting this out just in case there is something against this by design?

hmget returning array?

I don't get an object when I use hmget, to retrieve specified fields from a given hash:

hash =  {ingr1: eggs, ingr2: peppers, ingr3: potatoes}
hmget(hash, ingr1, ingr2)
// [eggs, peppers]

Curious if I am wrong to suggest this is wonky. hgetall() returns field:value.

Auto-closing of connections

Using fictorial's redis-client, I was able to set an auto-close mode for tests using code similar to:

client = redis.createClient();
client.addListener("drained", function() {
  this.close();
});

It automatically closed the connection to Redis whenever there were no items remaining in the queue to process (in or outbound). For tests, it allowed me to not worry about explicitly closing the connection (and cause running tests to fail) in order for the process to exit normally (otherwise it sits and hangs, as something is still open/running).

Is there a way to do something similar using this client?

Is there a different pattern I should be using for my tests? E.g., client per test with a close() call inside a finally block?

One time callback

Hi,

how can I assign a one time callback to an event? Node.js documentation says that eventEmitters have a .once function, but when I try to use it with a redis client I get this sort of error:

redis.once("idle", inner_recurse);
    ^
TypeError: Object #<a RedisClient> has no method 'once'
  at Timer.callback (/home/skejti/Plateboiler/rapid.queue/worker.js:23:9)
  at node.js:607:9

What I want to achieve is to only go into recursion when the command queue is empty. So I first check that the queue length is 0 and if it's not I assign a one time callback to the "idle" event. This is to prevent essentially race conditions with recursion being called every time the queue is emptied anywhere in the algorithm's flow.

Am I going about it the wrong way perhaps?

Disconnect/Reconnect does not reset pub/sub variable

Restarted redis. App got into the following loop trying to re-authenticate.

26 Sep 19:40:50 - redis client reconnecting
26 Sep 19:40:50 - Error: { message: 'Connection in pub/sub mode, only pub/sub commands may be used'
, stack: [Getter/Setter]
}

[ repeat ... ]

Client sending wrong command to server - getting stuck in loop.

Getting a strange error. Happens pretty regularly. Node process breaks after about 30-60 mins of running. I get a message like this:

no callback to send error: 'ERR unknown command \'}\''
Exception in RedisReplyParser: Error: ERR unknown command '}'
at RedisClient.return_error (/disk1/home/logplex/vendor/node_redis/index.js:443:15)
at RedisReplyParser.<anonymous>      (/disk1/home/logplex/vendor/node_redis/index.js:324:18)
at RedisReplyParser.emit (events:26:26)
at RedisReplyParser.send_error (/disk1/home/logplex/vendor/node_redis/index.js:236:14)
at RedisReplyParser.execute (/disk1/home/logplex/vendor/node_redis/index.js:91:22)
at RedisClient.on_data (/disk1/home/logplex/vendor/node_redis/index.js:429:27)
at Stream.<anonymous> (/disk1/home/logplex/vendor/node_redis/index.js:351:14)
at Stream.emit (events:26:26)
at IOWatcher.callback (net:489:16)
at node.js:764:9

The ERR unknown command is coming from inside redis. It apparently was sent a '}' command. The client can't figure out what command send this and throws an
exception. A fraction of a second later the error will repeat but with more info following the ERR. It will spiral out of control eventually looking like t
his:

no callback to send error: 'ERR unknown command \'=>""}}}\':0+OK:0:501:0+OK:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:501:0:0:0:501:0:0:0:0:0:501:0:0:0:0+OK:0:0:0:0:501:0+OK:0:0:0:0:0:0:0:501:0:0:0:501:0:501:0:501:0:0:0:0:0:0:0:0:0:0:0:0+OK:0:0:0:0:0:501:0:0:0:501:0:0:0:0:0:501:0:0:0:501:0:0:0:0:0:0:0:0:0+OK:0:0:0:0:0:0:0:0:0:0+OK:0+OK:0:0:0:0:0:0:501:0:501:0+OK:0:0:0:0+OK:0:0:0:0:0:0:0+OK:0:501:0:0:0:501:0:0:0:0:0:0+OK:0:0:0:0:501:0+OK:0:0:0:0:0:0:0:0:0:0+OK:0:0:0:501:0:0:0:0:0:0:501:0:0:0:0:0:0:0:0:0:0:501:0:0:0:0:0:0:0:0:0+OK:0:0:0:0:0:0:0:501:0:501:0+OK:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:501:0:0:0:0:0:0:0:501:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:501:0:501:0:501:0:501:0:0:0:0:0:501:0:0:0:0:0:0:0:0:0:0:0:0:501:0:0:0:0:0:0:0:0:0+OK:0:0:0:0:0:0:0:0:0:0:501:0:0:0:501:0:0:0:0:0:0:0:501:0:0:0:0:0:0:0:0:0:0:501:0:0+OK:0:0:501:0:0:0:501:0:0:0+OK:0:0:0:0:0:0:0:501:0:0:0:501:0+OK:0:501:0:0:0:501:0:501:0:0:0:0:0+OK:0:0:0:0:0+OK:0:0:0:501' 
Exception in RedisReplyParser: Error: ERR unknown command '=>""}}}':0+OK:0:501:0+OK:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:501:0:0:0:501:0:0:0:0:0:501:0:0:0:0+OK:0:0:0:0:501:0+OK:0:0:0:0:0:0:0:501:0:0:0:501:0:501:0:501:0:0:0:0:0:0:0:0:0:0:0:0+OK:0:0:0:0:0:501:0:0:0:501:0:0:0:0:0:501:0:0:0:501:0:0:0:0:0:0:0:0:0+OK:0:0:0:0:0:0:0:0:0:0+OK:0+OK:0:0:0:0:0:0:501:0:501:0+OK:0:0:0:0+OK:0:0:0:0:0:0:0+OK:0:501:0:0:0:501:0:0:0:0:0:0+OK:0:0:0:0:501:0+OK:0:0:0:0:0:0:0:0:0:0+OK:0:0:0:501:0:0:0:0:0:0:501:0:0:0:0:0:0:0:0:0:0:501:0:0:0:0:0:0:0:0:0+OK:0:0:0:0:0:0:0:501:0:501:0+OK:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:501:0:0:0:0:0:0:0:501:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:501:0:501:0:501:0:501:0:0:0:0:0:501:0:0:0:0:0:0:0:0:0:0:0:0:501:0:0:0:0:0:0:0:0:0+OK:0:0:0:0:0:0:0:0:0:0:501:0:0:0:501:0:0:0:0:0:0:0:501:0:0:0:0:0:0:0:0:0:0:501:0:0+OK:0:0:501:0:0:0:501:0:0:0+OK:0:0:0:0:0:0:0:501:0:0:0:501:0+OK:0:501:0:0:0:501:0:501:0:0:0:0:0+OK:0:0:0:0:0+OK:0:0:0:501
at RedisClient.return_error (/disk1/home/logplex/vendor/node_redis/index.js:443:15)
at RedisReplyParser.<anonymous> (/disk1/home/logplex/vendor/node_redis/index.js:324:18)
at RedisReplyParser.emit (events:26:26)
at RedisReplyParser.send_error (/disk1/home/logplex/vendor/node_redis/index.js:236:14)
at RedisReplyParser.execute (/disk1/home/logplex/vendor/node_redis/index.js:91:22)
at RedisClient.on_data (/disk1/home/logplex/vendor/node_redis/index.js:429:27)
at Stream.<anonymous> (/disk1/home/logplex/vendor/node_redis/index.js:351:14)
at Stream.emit (events:26:26)
at IOWatcher.callback (net:489:16)
at node.js:764:9

I've not been able to debug it further.

has no method 'split'

I just upgraded to Node.js v0.4.1 and saw this error "has no method 'split'" from index.js line 182 -
var lines = res.split("\r\n"), obj = {}, retry_time;

Quick monkeying seems to show that "res" is a Buffer not a String, and when I changed this line to

var lines = res.toString().split("\r\n"), obj = {}, retry_time;

everything seems to be fine. Is this a bug?

Error after connect when Redis is loading the dataset in memory

The connect event is emitted, but Redis is not necessarily ready if it is still loading keys from disk. All calls return an error "LOADING Redis is loading the dataset in memory". It would be preferable to either, delay the connect event until after Redis is ready, or to add a subsequent event (eg. 'ready') to indicate to clients that Redis is ready to handle commands.

This could also cause offline_queueed commands to also fail if they are executed inbetween connect and LOADING the dataset.

pipelining in node_redis

Hi,
I wonder if that driver supports redis pipelining? I didn't find any samples. Maybe it pipelines by default?

idiomatic HMSET

I was comparing redis-node and node-redi. As to the HMSET commnad, I think redis-node uses a more idiomatic and handy way showed as follows:

// The commands are also idiomatic
client.hmset("hash", { t: "rex", steg: "asaurus" }, function (err, status) {
if (err) throw err;
sys.log(status); // true
});

My question is, would you consider or have a plan to implement hmset like this ?

Can't auth

Hi,

I'm trying to connect to a redistogo instance but the auth example I found in the node_redis source code doesn't work.

This is what I'm doing:

var redis = require("redis"),
    client = redis.createClient(MYPORT, "catfish.redistogo.com");

client.on("error", redis.print);

// whenever the client connects, make sure to auth
client.on("connect", function () {
    client.auth("MYPASS", redis.print);
});

client.auth("MYPASS");

I just got a

Error: Ready check failed: Error: Error: ERR operation not permitted

Using the same credentials with redis-cli I can successfully connect with my istance.

Versions:
$ npm list installed redis
npm info it worked if it ends with ok
npm info using [email protected]
npm info using [email protected]
[email protected] active installed Wrapper for reply processing code in hiredis
[email protected] active installed Redis client library

Cheers,
Giacomo

web_server.js: Cannot find module 'redis'

node v0.3
redis v2.2 antirez git

wfm most test.js

at resolveModuleFilename (node.js:265:13)
at loadModule (node.js:231:20)
at require (node.js:291:14)
at Object. (/Users/jaymini/node_redis/examples/web_server.js:4:20)
at Module._compile (node.js:348:23)
at Object..js (node.js:356:12)
at Module.load (node.js:279:25)
at Array. (node.js:370:24)
at EventEmitter._tickCallback (node.js:42:22)
at node.js:634:9

Broken pipe and Stream not writable errors

Hi,

I seem to be getting this unhandled exception. Not sure why or how it happens, but it keeps crashing my processes.

Any idea what I should do to avoid this?

node.js:50
  throw e;
  ^
Error: EPIPE, Broken pipe
  at Stream._writeImpl (net:316:14)
  at Stream._writeOut (net:748:25)
  at Stream.write (net:681:17)
  at RedisClient.send_command   (/usr/local/lib/node/.npm/redis/0.3.5/package/index.js:645:16)
  at RedisClient.<anonymous>   (/usr/local/lib/node/.npm/redis/0.3.5/package/index.js:718:27)
  at Object.log (/home/skejti/Plateboiler-js/lib/logging.js:8:11)
  at Object.info (/home/skejti/Plateboiler-js/lib/logging.js:13:45)
  at /home/skejti/Plateboiler-js/plateboiler.js:65:16
  at Object.onload (/home/skejti/Plateboiler-js/jsdom/lib/jsdom.js:59:32)
  at /home/skejti/Plateboiler-js/jsdom/lib/jsdom/browser/index.js:360:1

re-auth on reconnect

After sending an auth command, it can be surprising when an auto-reconnect happens and you need to send auth again. We should remember the auth and re-send it on reconnect.

typo

"client.get() is the same as clieint.GET()"

Why keep Buffers?

Is there a good reason, why only single line requests are converted to strings and others kept as Buffers. I know that converting to strings would take a little more CPU, but to use the answers, we still need to to do that, so there is no almost no win. I think we should be consistent about the result and always convert to string (except those that always return integers). So.. is there something I'm missing or what's the reason?

outside of client's scope?

Hi there. I'm not sure if I have run up against a limitation of this module, or of my skill. I can't seem to do anything with the return of a query outside of the optional function. The only way I can do anything to the data, is to put everything inside that function, i.e. passing the data as locals (res.render). Can you please set me straight?

For instance, I unable to attach the reply to a variable.

var data = client.get("test", function(err, reply){})

Similarly, I am unable to do this:

var data;
client.get("test", function(err, reply){
data = reply.toString()
})  // data undefined 

Only this works, but it is not the ideal construction:

client.get("tester", function(err, data) {
res.render('index', {
    locals: {
      title: '',
      body: data
   }
     })
});

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.