Node.jsでRedisと接続する

2017年3月26日その他

かなりメモ的ですが…
Node.jsでRedisを利用するには、まずは、Redisのモジュールをインストールが必要です。

npm install redis

コマンドから、データベースを入力して、コマンドに表示する。サンプルです。

sample.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
var redis = require('redis');
var client = redis.createClient();
var params = { author: process.argv[2], quote: process.argv[3] };
 
client.on('ready', function () {
    if (params.author && params.quote) {
        var randKey = "Quotes:" + (Math.random() * Math.random()).toString(16).replace('.', '');
        client.hmset(randKey, {
            "author": params.author,
            "quote": params.quote
        });
        client.sadd('Author:' + params.author, randKey);
    }
     
    if (params.author) {
        client.smembers('Author:' + params.author, function (err, keys) {
            keys.forEach(function (key) {
                client.hgetall(key, function (err, hash) {
                    if (err) {console.log(err); return;}
                    console.log('%s: %s', hash.author, hash.quote);
                });
            });
            client.quit();
        });
    } else {
        client.quit();
    }
});