0
0
Redisquery~5 mins

Redis with Node.js (ioredis)

Choose your learning style9 modes available
Introduction

Redis is a fast database that stores data in memory. Using Node.js with ioredis lets you easily talk to Redis from your JavaScript code.

You want to save user session data quickly for a website.
You need to cache data to make your app faster.
You want to count things like page views in real time.
You want to store simple key-value pairs for quick access.
You want to use Redis features like lists or sets from your Node.js app.
Syntax
Redis
const Redis = require('ioredis');
const redis = new Redis();

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

// Get a key
const value = await redis.get('key');
Use require('ioredis') to load the library.
Create a new Redis client with new Redis() to connect to Redis server.
Examples
This example saves the name 'Alice' and then reads it back.
Redis
const Redis = require('ioredis');
const redis = new Redis();

await redis.set('name', 'Alice');
const name = await redis.get('name');
console.log(name);
This example increases a number stored in 'counter' by 1 and prints it.
Redis
const Redis = require('ioredis');
const redis = new Redis();

await redis.incr('counter');
const count = await redis.get('counter');
console.log(count);
Sample Program

This program connects to Redis, saves a greeting message, reads it back, prints it, and then disconnects.

Redis
const Redis = require('ioredis');

async function run() {
  const redis = new Redis();

  await redis.set('greeting', 'Hello, Redis!');
  const message = await redis.get('greeting');

  console.log(message);
  await redis.disconnect();
}

run();
OutputSuccess
Important Notes

Make sure Redis server is running before you connect.

Use await because ioredis commands return promises.

Always disconnect your Redis client when done to free resources.

Summary

ioredis lets Node.js talk to Redis easily.

Use set and get to store and read data.

Remember to handle asynchronous calls with await.