尋常でないもふもふ

a software engineer blog

node_redisでscanコマンド

ググってもサンプルがでてこないので悩んだ。
node_redis では、個別にコマンドの実装があるわけではなく、send_command 関数を共通で使う実装 になっている。
公式ドキュメントの SCAN – Redis をみると SCAN cursor [MATCH pattern] [COUNT count] という書式になっているため、SCAN 以降を args に渡して実行すれば良い。

方式1

引数に cursor, 'MATCH' という文字列, pattern, 'COUNT'という文字列, count をそのまま指定する。

client.scan(0, 'match', 'val*', 'count', 5, function(err, result) {
  if (err) throw err;
  console.log('cursor is ' + result[0]);
  console.log(result[1].join(','));
}

方式2

あらかじめ引数を配列にしておく。

var args = [0, 'match', 'val*', 'count', 5];
client.scan(args, function(err, result) {
  if (err) throw err;
  console.log('cursor is ' + result[0]);
  console.log(result[1].join(','));
}

実行結果

結果は配列で返り、要素1にカーソル、要素2に取得した値が入っている。

cursor is 0
val1, val2, val3