redis-lua2js

convert redis lua scripts to a useful node module
Install
$ npm install --save-dev redis-lua2js
Usage
This module is not meant to be used on its own, but rather as part of another module, such as gulp-redis-lua2js or hook-redis-lua. In here, I will demonstrate the usage with the help of require-from-string:
pdel.lua:
local function deleteKeys (keys)
for i, name in ipairs(keys) do
redis.call("DEL", name)
end
end
if type(redis.replicate_commands) == 'function' and redis.replicate_commands() then
local count = 0
local cursor = "0"
local keys
repeat
cursor, keys = unpack(redis.call("SCAN", cursor, "MATCH", KEYS[1]))
count = count + #keys
deleteKeys(keys)
until cursor == "0"
return count
else
local keys = redis.call("KEYS", KEYS[1])
deleteKeys(keys)
return #keys
end
index.js:
import Redis from 'ioredis';
import fs from 'fs';
import path from 'path';
import lua2js from 'redis-lua2js';
const ioredis = new Redis();
const lua = fs.readFileSync(path.join(__dirname, 'pdel.lua'));
const js = lua2js(lua);
const pdel = requireFromString(js);
pdel.install(ioredis);
ioredis.pdel('*');
console.log(pdel.name);
console.log(pdel.numberOfKeys);
console.log(pdel.lua);
Note: supports Node 4+
API
lua2js(lua, { name, numberOfKeys })
Takes the contents of a lua script and outputs a node module, as a string, which can be used to load the script into a redis client such as ioredis easily.
lua
Type: string, the contents of a lua script
name
Type: string, optional, default: it is parsed from the comments of the lua script, as demonstrated in the Usage section
The name of the redis command, will be used when installing to ioredis
numberOfKeys
Type: string, optional, default: it is parsed from the comments of the lua script, as demonstrated in the Usage section
The number of keys that the redis command accepts
The parsed module will export the following:
name
Type: string, contains the name from the API above
numberOfKeys
Type: integer, contains the value of the number of keys argument from the API above
lua
Type: string, contains the contents of the lua script, useful for manually installing the script, for example, with ioredis.defineCommand
install(ioredis, { name, numberOfKeys })
Takes an instance of ioredis and executes ioredis.defineCommand with the required arguments.
ioredis
Type: instance of ioredis
name
Type: string, optional, default: the same as the exported name
Used to override the default name, if needed
numberOfKeys
Type: string, optional, default: the same as the exported number of keys
Used to override the default number of keys, if needed
Tests
npm test
License
See the LICENSE file for license rights and limitations (MIT).