How to save javascript array as redis list

The following code saves the entire array as a single value in the redis list. But I want to save the values โ€‹โ€‹of the array individually. How can I do it?

PS Sorry for the bad English.

var redis = require('redis'), client = redis.createClient(); var arr = [1,2,3]; client.rpush('testlist',arr); 
+6
source share
2 answers

Use multi() to pipeline several 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) { }) 

Finally, call exec() to send the redis commands.

+15
source

Even if @gimenete's answer works, the best way to do what you want is to pass list items as arguments to rpush like this:

 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 : - one team will be transferred to Redis

against : - angle register: .apply will trigger RangeError: Maximum call stack size exceeded if the argument list passed to rpush is too long (just over 100,000 items for v8).

From MDC:

The consequences of using a function with too many arguments (I think more than tens of thousands of arguments) differ in different machines (JavaScriptCore has a hard-coded argument limit of 65536), because the limit (indeed even the nature of any behavior with an excessively large stack) is not specified. Some engines throw an exception. More disastrous, others will arbitrarily limit the number of arguments actually passed to the application function.

+6
source

Source: https://habr.com/ru/post/957255/


All Articles