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.
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.
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');
require('ioredis') to load the library.new Redis() to connect to Redis server.const Redis = require('ioredis'); const redis = new Redis(); await redis.set('name', 'Alice'); const name = await redis.get('name'); console.log(name);
const Redis = require('ioredis'); const redis = new Redis(); await redis.incr('counter'); const count = await redis.get('counter'); console.log(count);
This program connects to Redis, saves a greeting message, reads it back, prints it, and then disconnects.
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();
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.
ioredis lets Node.js talk to Redis easily.
Use set and get to store and read data.
Remember to handle asynchronous calls with await.
set method do in ioredis when used with Node.js?set in Redisset method is used to store data by assigning a value to a key in Redis.get retrieves data, del deletes data, and connection is handled separately.set stores data [OK]await is needed to get the resolved value.get retrieves the value; set stores data; getSync does not exist.await with get [OK]const Redis = require('ioredis');
const redis = new Redis();
async function test() {
await redis.set('color', 'blue');
const val = await redis.get('color');
console.log(val);
}
test();const Redis = require('ioredis');
const redis = new Redis();
function getValue() {
const value = redis.get('key');
console.log(value);
}
getValue();get method returns a Promise, so without await, value is a Promise object.value prints a Promise, not the actual stored value.JSON.stringify to convert object to string before storing, and JSON.parse to convert back after retrieving.set('session', JSON.stringify(session)) to store and JSON.parse(await get('session')) to retrieve -> Option BPass the test and this pattern moves unknown