In this short example we’ll learn how to use Redis Lua scripting in NodeJS. We will create simple script that sums two fields of hash in Redis.
Install Redis and Redis-scripto NodeJS modules:
1
| npm install redis redis-scripto
|
Redis-scripto loads and manages Lua scripts for you, so you don’t have to load them manually.
Create demo.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| var path = require('path'); redis = require('redis'), scripto = require('redis-scripto'), field1 = process.argv[2], field2 = process.argv[3], redisClient = redis.createClient(), scriptDir = path.resolve(path.dirname(__filename), 'lua'), scriptManager = new scripto(redisClient); scriptManager.loadFromDir(scriptDir); scriptManager.run('hadd', ['test'], [field1, field2], function(err, result) { console.log(result); });
|
Create ‘lua’ directory
Create lua/hadd.lua with following code. It gets values of two passed fields from test hash, sums them and returns.
1 2 3 4 5 6 7 8
| local key = KEYS[1] local field1 = ARGV[1] local field2 = ARGV[2] local n1 = tonumber(redis.call('hget', key, field1)) local n2 = tonumber(redis.call('hget', key, field2)) return n1 + n2
|
Than run redis-cli and add some values to test hash
1 2 3
| redis-cli hset test score1 22 hset test score2 33
|
Then run demo.js
1 2
| node demo score1 score2 55
|