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
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:
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 wroteredis-om
, which uses theredis
package, and while I’d be delighted if you used it, it’s not needed for what you are trying to do.I have also faced this error before. Then I installed
ioredis
package. Now it works well. Here’s my solution: