executing redis eval command to run Lua script in

2020-03-30 16:21发布

问题:

In Redis I run a Lua script through CLI like this:-

$ redis-cli --eval debug_script.lua key1 key2 key3 key4 , arg1 arg2

So, my Lua script accepts 4 keys and 2 arguments.

Now I want to run the same script in Node.js.

I am using this library for importing Redis in my app.

I didn't find any example which tells about the arguments of redisClient.eval(...) function for executing the Lua script.

Thus I am just hitting something random that might work. But nothing seems to work.

My app.js goes like this:

var redis = require("redis")
var client = redis.createClient();

// my hit and trial guess
client.eval(["script_file.lua", 1 "score" 0 10 , "meeting_type:email" meeting_status:close], function(err, res){
    console.log("something happened\n");
});

My question: How to execute below command using node.js, so that it returns the same thing as it does when executed through CLI(command-line-interface).

$ redis-cli --eval debug_script.lua key1 key2 key3 key4 , arg1 arg2

回答1:

Found some solutions:

Solution 1 )

var redis = require('redis')
var client = redis.createClient()
var fs = require('fs')

client.eval(fs.readFileSync('./debug_script.lua'), 4, key1, key2, key3, key4, arg1, arg2, function(err, res) {
  console.log(res);
});

Note: 4 (second argument of eval) represents the number of keys to be passed in the script.

Solution 2) Creates a child process and run CLI command.

var redis = require("redis");
var client = redis.createClient();

var exec = require('child_process').exec;

var cmd = 'redis-cli --eval debug_script.lua key1 key2 key3 key4 , arg1 arg2';


exec(cmd, function(error, stdout, stderr) {
    // command output is in stdout
        console.log("something happened \n");
        console.log(stdout);
    });