I am trying to implement redis into my nodejs and expressjs API REST, but for some reason I am getting the error The client is closed
.
- I´ve installed redis for windows
- I´ve ran
redis-server
in the cmd. - I´ve tested the redis cli by runing
redis-cli
and then passingping
.PONG
was logged as a result, so it is working.
Created a middleware init_redis.js
const redis = require('redis');
const createConnectedClient = async () => {
const client = redis.createClient({
host: 'localhost',
port: 6379,
});
client.on('error', (err) => {
console.log('Redis client error', err);
});
await client.connect();
return client;
};
module.exports = createConnectedClient;
I tried to test redis in my server.js
const createConnectedClient = require('./middleware/init_redis');
let redisClient;
(async () => {
try {
redisClient = await createConnectedClient();
redisClient.on('error', (err) => {
console.log('Redis client error', err);
});
} catch (error) {
console.error('Failed to connect to Redis:', error);
}
})();
(async () => {
if (redisClient) {
try {
await redisClient.set('foo', 'bar');
const value = await redisClient.get('foo');
console.log(value);
} catch (err) {
console.error('Error setting or getting key from Redis:', err);
}
}
})();
When I run my nodejs server, I get The client is closed
. Why is this happening if my redis server is running and I am connectinc my client?
If I do asynchronous functions to run the client, nothing is being logged in my console.
2
Answers
Assuming you are using the latest version of
redis
in npm ( 4.6.13 ), it is documented that the functioncreateClient
in the Redis package is asynchronous, meaning you must wait for the connection to be established for it to work correctly.Notice that you call createClient but do not handle the promise nor call
await
on the function call ( https://www.npmjs.com/package/redis#basic-example ).The line requiring the client (
const redisClient = require('./middleware/init_redis');
) creates the client, then the program attempts to use it immediately after, thus resulting in the error you are getting:The client is closed
; you are not allowing the client to successfully establish the connection before using the client.This should work: