Redis Script Utility for Node.js

2.0.1 · maintenance · verified Tue Apr 21

node-redis-script is a JavaScript library designed to simplify the execution of Lua scripts within Redis from Node.js applications. It abstracts the complexities of `EVAL` and `EVALSHA` commands, allowing developers to define scripts as strings and then execute them via a generated function. The current stable version is 2.0.1. It primarily focuses on providing a clean, function-oriented API for script management rather than requiring direct interaction with Redis `EVAL` commands. This library automatically handles script loading and caching using `EVALSHA` for efficiency, reducing network overhead after the initial script load. It offers flexibility by supporting both `node-redis` (v0.10+) and `ioredis` clients, allowing integration with existing Redis client setups.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to initialize a Redis client, define a Lua script, create a script function using `createScript`, and then execute it with specific keys and arguments. It showcases a common pattern for an atomic increment-and-expire operation.

import { createClient } from 'redis'; // or from 'ioredis'
import { createScript } from 'node-redis-script';

async function runRedisScript() {
  const redisClient = createClient();
  redisClient.on('error', (err) => console.log('Redis Client Error', err));
  await redisClient.connect();

  const incrbyExSrc = `
    local current
    current = redis.call('incrby',KEYS[1],ARGV[1])
    redis.call('expire',KEYS[1],ARGV[2]);
    return current
  `;

  // give it a redis client and script source
  const opts = { redis: redisClient }; // For ioredis: { ioredis: ioredisClient }
  const incrbyEx = createScript(opts, incrbyExSrc);

  // redis requires you to tell it how many keys to expect
  const numKeys = 1;
  const key = 'myCounterKey';
  const incr = 5;
  const ex = 60; // expire in 60 seconds

  const result = await incrbyEx(numKeys, key, incr, ex);
  console.log(`Current value of ${key}: ${result}`); // Should print 5 the first time, 10 the second, etc.

  await redisClient.disconnect();
}

runRedisScript().catch(console.error);

view raw JSON →