Skip to content

Instantly share code, notes, and snippets.

@snghnishant
Created August 25, 2022 16:04
Show Gist options
  • Save snghnishant/506922d5ae2a3524ec9d5840633576ed to your computer and use it in GitHub Desktop.
Save snghnishant/506922d5ae2a3524ec9d5840633576ed to your computer and use it in GitHub Desktop.
Redis Scan Stream Node.js
// Redis Client file
// const redis = require("redis");
// const { REDIS_HOST } = process.env;
// module.exports = () => {
// if (REDIS_HOST)
// return redis.createClient({
// url: `redis://${REDIS_HOST}:6379`
// });
// return redis.createClient();
// };
// scan stream tool
const { promisifyAll } = require("bluebird");
const redisClient = require("../lib/redisClient")();
const { promisify } = require("util");
const scanStream = promisify(redisClient.scan).bind(redisClient);
promisifyAll(redisClient);
// Recursive function to keep scanning
// pattern = commonKeyElement*.
// eg. - ltp_*
exports.scanAllKeys = async (pattern) => {
const found = [];
let cursor = "0";
try {
do {
const reply = await scanStream(cursor, "MATCH", pattern, "COUNT", "10"); // scan 10 keys at once
cursor = reply[0];
// console.log("Cursor at: ", cursor);
found.push(...reply[1]); // reply[1] is an array of matched keys.
} while (cursor !== "0"); // cursor will be at 0 when scan completes
} catch (error) {
console.log("Redis scan error: ", error);
}
return found;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment