SET And GET Value In Redis Using Node.js

Prerequisites:

  • Basic knowledge of Node.js
  • Code editors like Visual Studio 2019
  • If you new to Node.js? You must have to follow the link given below to set up a new Node.js API in Visual Studio.

How To Create Simple Node.js API In Visual Studio

SET ad GET key-value in Redis using Node.js API :

Let’s first create the Redis_demo.js file.
Before the start of implementing the project. we need to add npm packages to our node js project.

npm install express
npm install body-parser
npm install redis

Add dependencies in the Redis_demo.js file.

const express = require('express');
const app = express();
const bodyParser = require("body-parser");
const redis = require('redis');

Now Let’s create the Redis connection.

const client = redis.createClient({
    host: 'localhost',
    port: 6379
});
client.on('error', function (err) {
    console.log("----------in redis error----------")
    console.log(err);
    console.log("----------in redis error end----------")
})
client.on('connect', function() {
    console.log('Redis Connected!');
});

By default, the Redis port is 6379.

Let’s create a node js server.

const port = 3000;
app.listen(port, async () => {
    console.log(`Example app listening on port ${port}`)
    await client.connect();
});

Now add the below code in the Redis_demo.js file for SET and GET key-value from Redis.

app.get('/', async(req, res) => {
    try{
        var getData = await getSessionData(req.body.Key);
        res.status(200).send(getData);
    } catch(e){
        console.log(e);
        res.status(200).send(e);
    }
})

app.post('/user-message', async (req, res) => {        
    try{
        var createData = await createSessionData(req.body.Key, req.body.Value);
        res.status(200).send(createData);
    } catch(e){
        console.log(e);
        res.status(200).send(e);
    }
})


async function createSessionData(Key, Value){
    return new Promise(async function (resolve, reject) {
        try{
            var storeValue = await client.set(Key,Value);
            resolve(storeValue);
        }catch(e){
            console.log(e)
            resolve(0);
        }
    });
}

async function getSessionData(Key){
    return new Promise(async function (resolve, reject) {
        try{
            var getValue = await client.get(Key);
            resolve(getValue);
        }catch(e){
            console.log(e)
            resolve(0);
        }
    });
}

And here’s the final version of the Redis_demo.js.js file :

const express = require('express');
const app = express();
const bodyParser = require("body-parser");
const redis = require('redis');
const client = redis.createClient({
    host: 'localhost',
    port: 6379
});
client.on('error', function (err) {
    console.log("----------in redis error----------")
    console.log(err);
    console.log("----------in redis error end----------")
})
client.on('connect', function() {
    console.log('Redis Connected!');
});
app.use(
    bodyParser.urlencoded({
        extended: true,
        limit: "50mb",
        parameterLimit: 1000000
    })
);
app.use(bodyParser.json());
const port = 3000;

app.listen(port, async () => {
    console.log(`Example app listening on port ${port}`)
    await client.connect();
})

app.get('/', async(req, res) => {
    try{
        var getData = await getSessionData(req.body.Key);
        res.status(200).send(getData);
    }catch(e){
        console.log(e);
        res.status(200).send(e);
    }
})

app.post('/user-message', async (req, res) => {        
    try{
        var createData = await createSessionData(req.body.Key, req.body.Value);
        res.status(200).send(createData);
    }catch(e){
        console.log(e);
        res.status(200).send(e);
    }
})


async function createSessionData(Key, Value){
    return new Promise(async function (resolve, reject) {
        try{
            var storeValue = await client.set(Key,Value);
            resolve(storeValue);
        }catch(e){
            console.log(e)
            resolve(0);
        }
    });
}

async function getSessionData(Key){
    return new Promise(async function (resolve, reject) {
        try{
            var getValue = await client.get(Key);
            resolve(getValue);
        }catch(e){
            console.log(e)
            resolve(0);
        }
    });
}
  • SET value, set the key value in Redis server.

  • GET value, get the value from Redis server.

Conclusion:

If you’re trying to find a quick and powerful knowledge store to use together with your NodeJS applications, Redis may be a natural choice. during this article, we learned that these 2 technologies are used along. With our example to use as a guide, you’ll be ready to add Redis practicality to your own NodeJS applications.

That’s how you can SET & GET Value in Redis Using Node.js.

If you are new to Redis and you don’t have installed Redis On your machine then you can follow this link on how to install Redis in our system.

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories