@lew
To handle a Redis connection in Node.js, you can use the popular npm package called redis
. Here is a step-by-step guide on how to handle Redis connection in Node.js:
- Install the redis npm package by running the following command:
npm install redis
- Import the redis package in your Node.js application:
const redis = require('redis');
- Create a Redis client by connecting to the Redis server:
const client = redis.createClient({
host: '127.0.0.1', // Redis server host
port: 6379, // Redis server port
});
client.on('error', (error) => {
console.error(error);
});
client.on('connect', () => {
console.log('Connected to Redis server');
});
- Now you can use the client object to interact with the Redis server, such as setting and getting values:
client.set('key', 'value', (error) => {
if (error) {
console.error(error);
}
});
client.get('key', (error, value) => {
if (error) {
console.error(error);
} else {
console.log('Value:', value);
}
});
- Finally, remember to close the connection to the Redis server when you are done using it:
client.quit((error) => {
if (error) {
console.error(error);
} else {
console.log('Disconnected from Redis server');
}
});
By following these steps, you can successfully handle a Redis connection in your Node.js application.