首页 > 解决方案 > 如何在nodejs redis中递归扫描键

问题描述

根据这里提出的解决方案,我编写了这个函数来递归扫描 NodeJS Redis 中的键 -给定模式的node-redis :

RedisStore.prototype.scan = function(params, callback, cursor = '0', returnSet = new Set()) {
    var self = this;
    var options = {
        pattern: '',
        match: 'MATCH',
        count: 100
    };
    for (var attrname in params) {
        options[attrname] = params[attrname];
    }
    var count = '' + options.count;
    self.client.scan(cursor, options.match, options.pattern, 'COUNT', count,
        (err, reply) => {
            if (err) {
                return callback(err, null);
            }
            cursor = reply[0];
            if (cursor === '0') { // scan completed
                return callback(null, Array.from(returnSet));
            } else {
                var keys = reply[1];
                keys.forEach(function(key, i) {
                    returnSet.add(key);
                });
                return self.scan(options, callback, cursor, returnSet);
            }
        });
} // scan

我之前插入了一个带有前缀test:+ 一些字符串的键,但正在扫描

var res = await store.scan({
    pattern: 'test:*',
    count: 10
    });

将具有作为起始值cursor = '0'returnSet = new Set(), 似乎没有找到任何东西,因此导致为空resultSet且未达到0光标退出条件。为什么?

标签: javascriptnode.jsredis

解决方案


推荐阅读