Redis®*: Redis code example using Node.js
This documentation is part of the Rank users in real time guide. You can view the complete guide here: Learn how to rank 2 million users by score in real time using Redis.
👋 Welcome to the Stackhero documentation!
Stackhero provides a ready-to-use Redis cloud solution that delivers numerous advantages, including:
- Redis Commander web interface included.
- Unlimited message size and transfers.
- One-click simplified updates.
- Optimal performance and enhanced security thanks to a private, dedicated infrastructure.
Save time and make your life easier: it only takes 5 minutes to try Stackhero's Redis cloud hosting solution!
After validating the concept in Redis Commander, it is time to integrate Redis into real-world code. Our client uses Node.js and below is an example using ioredis as the client:
const Redis = require('ioredis');
(async () => {
// Set Redis credentials
// If you use Stackhero, you will find these on the Stackhero dashboard
const redis = new Redis({
host: '<redisServerHost>',
password: '<redisServerPassword>',
port: <PORT_TLS>, // <PORT_CLEAR> is for clear connections and <PORT_TLS> is for TLS. TLS should be used.
tls: {}, // Provide an empty object to activate TLS
lazyConnect: true
});
// Connect to Redis
await redis.connect();
// Add users
await redis.zadd('usersScores', 11, 'userId1');
await redis.zadd('usersScores', 54, 'userId2');
await redis.zadd('usersScores', 24, 'userId3');
// Retrieve userId1 score
const score = await redis.zscore('usersScores', 'userId1');
console.log('userId1 has ' + score + ' points');
// Retrieve userId1 rank position
const rankPosition = await redis.zrevrank('usersScores', 'userId1');
console.log('userId1 is ranked at position ' + rankPosition);
// Disconnect from Redis
await redis.disconnect();
})();
This simple yet powerful code snippet is ideal for managing real-time ranking data.