0
0
RedisHow-ToBeginner · 4 min read

How to Use ioredis in Node.js: Simple Guide with Examples

To use ioredis in Node.js, first install it with npm install ioredis. Then, create a Redis client using new Redis(), and use methods like set and get to store and retrieve data asynchronously.
📐

Syntax

The basic syntax to use ioredis involves importing the library, creating a Redis client, and calling Redis commands as methods on that client.

  • const Redis = require('ioredis'); - imports the ioredis library.
  • const redis = new Redis(); - creates a new Redis client connected to the default Redis server.
  • redis.set(key, value) - sets a value for a key.
  • redis.get(key) - retrieves the value of a key.
javascript
const Redis = require('ioredis');
const redis = new Redis();

// Set a key
redis.set('key', 'value');

// Get a key
redis.get('key').then(result => {
  console.log(result);
});
💻

Example

This example shows how to connect to Redis, set a key-value pair, and then get and print the value asynchronously using async/await.

javascript
const Redis = require('ioredis');

async function runExample() {
  const redis = new Redis(); // Connect to localhost:6379 by default

  await redis.set('greeting', 'Hello, ioredis!');
  const value = await redis.get('greeting');

  console.log('Stored value:', value);

  redis.disconnect();
}

runExample();
Output
Stored value: Hello, ioredis!
⚠️

Common Pitfalls

Common mistakes when using ioredis include:

  • Not waiting for asynchronous commands to complete before using their results.
  • Forgetting to handle connection errors or closing the connection properly.
  • Using callbacks instead of promises or async/await, which can lead to messy code.

Always use async/await or .then() to handle Redis commands and close the connection with redis.disconnect() when done.

javascript
/* Wrong way: ignoring async nature */
const Redis = require('ioredis');
const redis = new Redis();

redis.set('key', 'value');
const val = redis.get('key'); // val is a Promise, not the value
console.log(val); // Prints: Promise { <pending> }

/* Right way: using async/await */
async function correctUsage() {
  await redis.set('key', 'value');
  const val = await redis.get('key');
  console.log(val); // Prints: value
  redis.disconnect();
}
correctUsage();
Output
Promise { <pending> } value
📊

Quick Reference

CommandDescriptionExample
new Redis()Create a new Redis client connectionconst redis = new Redis();
redis.set(key, value)Set a string value for a keyawait redis.set('name', 'Alice');
redis.get(key)Get the string value of a keyconst val = await redis.get('name');
redis.del(key)Delete a keyawait redis.del('name');
redis.disconnect()Close the Redis connectionredis.disconnect();

Key Takeaways

Install ioredis with npm and import it using require('ioredis').
Create a Redis client with new Redis() to connect to your Redis server.
Use async/await or promises to handle Redis commands like set and get.
Always disconnect the client with redis.disconnect() when finished.
Handle errors and connection issues to avoid runtime problems.