How to save javascript array as redis list


The following code save the whole array as single value in redis list. But I want to save array values individually. How can I do it?

P.S So sorry for poor English.

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

var arr = [1,2,3];

Problem courtesy of: user2522545


Use multi() to pipeline multiple commands at once:

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

var arr = [1,2,3];

var multi = client.multi()

for (var i=0; i<arr.length; i++) {
    multi.rpush('testlist', arr[i]);

multi.exec(function(errors, results) {


And finally call exec() to send the commands to redis.

Solution courtesy of: gimenete


Even if @gimenete answer works, the best way to do what you want is to forward the list elements as arguments to rpush like so:

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

var arr = [1,2,3];
client.rpush.apply(client, ['testlist'].concat(arr));

// ... or with a callback
client.rpush.apply(client, ['testlist'].concat(arr).concat(function(err, ok){
  console.log(err, ok);

Pros: - a single instruction will be transmited to Redis

Cons: - a corner-case: .apply will throw a RangeError: Maximum call stack size exceeded if the arguments list length passed to rpush is too large (a little over 100 000 items for v8).

From MDC:

The consequences of applying a function with too many arguments (think more than tens of thousands of arguments) vary across engines (JavaScriptCore has hard-coded argument limit of 65536), because the limit (indeed even the nature of any excessively-large-stack behavior) is unspecified. Some engines will throw an exception. More perniciously, others will arbitrarily limit the number of arguments actually passed to the applied function.

Discussion courtesy of: FGRibreau

This recipe can be found in it's original form on Stack Over Flow.