Home > Back-end >  Redis giving error even after redis connected in nodejs
Redis giving error even after redis connected in nodejs

Time:02-26

I have redis installed on my system and its running as well. redis installed and running

from node application, im using below code to work with redis.

redis.js

    const redis = require("redis");

let client = redis.createClient(6379, '127.0.0.1', {});

let isRedis = false;

client.on("connect", function () {
    console.log(`connected to redis`);
    isRedis = true;
});


client.on("error", function (err) {
    console.log("redis connection error "   err);
    throw err;
});

client.on("end", function (err) {
    console.log("redis connection end "   err);
});

module.exports = {
    SetRedis,
    GetKeys,
    GetRedis,
    GetKeyRedis,
    delRedis
};

im using node index.js command to run the application which should also give me "connected to redis" when the connection is established, but i'm not getting this message on my console .

the npm package is also present in package.json

enter image description here

CodePudding user response:

I guess you are making mistake while making connection. It should have been

let client = redis.createClient('127.0.0.1', 6379, {});

rather than

let client = redis.createClient(6379, '127.0.0.1', {});

CodePudding user response:

Node Redis 4.x doesn't allow you to pass in discrete arguments for the host and port. The canonical example of connecting to Redis with Node Redis is this:

import { createClient } from 'redis';

(async () => {
  const client = createClient();

  client.on('error', (err) => console.log('Redis Client Error', err));

  await client.connect();

  await client.set('key', 'value');
  const value = await client.get('key');
})();

If you want to connect to somewhere other than localhost on port 6379, I recommend using a URL. Like this:

createClient({ url: 'redis://awesome.redis.server:6380' });

But if you want finer control, you can find all the gritty configuration options in the documentation on GitHub.

  • Related