Monday, 12 June 2017

Node js Redis tutorial - Quick Start

Install redis in nodeJS, Make redis connection and stored data in redis, Get data from redis, update and delete the data from redis.

Question: How to install redis module with node?
npm install redis




Question: How to include redis in nodeJS Project?
var redis = require("redis");



Question: How to connect to redis with nodeJS?
var client = redis.createClient();

//On connection
client.on('connect', function() {
    console.log('connected');
});

//On error of connection
client.on('error', function() {
    console.log('error');
});



Question: How to Store data/Get Data/ Delete data in redis with nodejs?
Store single value
client.set('technology', 'NodeJS');

Get Stored value
client.get('technology');

Delete Stored value
client.del('technology', function(err, reply) {
    console.log(reply);
});



Question: How to check Stored value exist OR Not
client.exists('technology', function(err, reply) {
    if (reply === 1) {
        console.log('Stored in Redis');
    } else {
        console.log('Not Stored in Redis');
    }
});




Question: What is HMSET in nodeJS?
HMSET is like hset but it allow to store value in "key/value" paris.



Question: How to store data in key/value pairs in redis?
client.hmset('frameworks_list', {
    'javascript': 'AngularJS',
    'css': 'Bootstrap',
    'node': 'Express'
}, function(err, msg) {
    if (err) {
        console.log("Error During save the data");
    }
    //console.log(msg);//ok    
});




Question: How to get data which was stored with hmset redis?
client.hgetall('frameworks_list', function(err, msg) {
    if (err) {
        console.log("Error During save the data");
    }
    //console.log(msg);//{javascript: 'AngularJS', css: 'Bootstrap', node: 'Express' }
});



Question: How to store unique values in redis?
client.sadd(['emails', 'abc1@no-spam.ws', 'abc2@no-spam.ws', 'abc3@no-spam.ws'], function(err, msg) {
});



Question: How to get stored values which was set sadd with in redis?
client.smembers('emails', function(err, msg) {
    
});