Skip to content

Instantly share code, notes, and snippets.

@jdrydn
Last active March 16, 2016 18:08
Show Gist options
  • Save jdrydn/93fbd4abdf61fac90f16 to your computer and use it in GitHub Desktop.
Save jdrydn/93fbd4abdf61fac90f16 to your computer and use it in GitHub Desktop.
module.exports = function scanEach(redis, opts, eachFn, callback) {
var scan_args = [ opts.cursor || 0 ];
if (opts.prefix) scan_args.push('MATCH', opts.prefix);
if (opts.count) scan_args.push('COUNT', opts.count);
scan_args.push(function (err, results) {
if (err) return callback(err);
if (!Array.isArray(results)) return callback(new Error('Invalid results from redis SCAN command'));
var nextCursor = parseInt(results.shift() || 0, 10);
var items = results.shift() || [];
if (!items.length && !nextCursor) return callback();
var nextScan = {
cursor: nextCursor,
prefix: opts.prefix,
count: opts.count
};
if (items.length) eachFn(results.shift() || [], function (err) {
if (err) return callback(err);
if (!nextCursor) return callback();
scanEach(redis, nextScan, eachFn, callback);
});
else scanEach(redis, nextScan, eachFn, callback);
});
// console.log(scan_args);
redis.scan.apply(redis, scan_args);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment