skip to Main Content

I am trying to connect to my online redis database.

const redis = require('redis');

const client = redis.createClient({
  password: '<password>',
  socket: {
      host: <host>
      port: <port>
  }
});

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

client.on('error', function(err) {
  console.error('Error connecting to server: ', err); 
});

client.set('mykey', 'myvalue', function(err, result) { 
  if (err) {
    console.error('Error setting value - : ', err);
  } else {
    console.log('Value set - ', result);
  }
});

However, when attempting to execute the code, an error of "Unhandled Runtime Error: Error: The client is closed" arises. I have observed that some individuals have recommended invoking the "Connect" method on the client; nonetheless, this results in the error message "client.connect" or "net.connect" is not a function. I am seeking guidance on how to address this issue.

For the purpose of connecting to my Redis database, I have installed the following dependencies using the npm package manager: redis, ioredis, redis-om, and node-redis.

I have also replaced the values , , and with the values given to me by redis.

2

Answers


  1. This is the Node Redis 3.x way of doing things. Node Redis 4.x uses Promises instead of callback. Here’s the connect example from the top of the README that shows you the preferred way of doing this:

    import { createClient } from 'redis';
    
    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');
    await client.disconnect();
    

    Note that you should only need the redis package for what you are trying to do. It is also the official Node.js client from Redis. I wrote redis-om, which uses the redis package, and while I’d be delighted if you used it, it’s not needed for what you are trying to do.

    Login or Signup to reply.
  2. I have also faced this error before. Then I installed ioredis package. Now it works well. Here’s my solution:

    import Redis from "ioredis";
    
    const client = new Redis({
      host: <host>,
      port: <port>,
      password: <password>,
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search