ioredis is a robust, full-featured Redis client for Node.js. It supports clusters, sentinels, streams, pipelining, and Lua scripting — everything you need for production Redis usage.
Installation
npm install ioredis
Basic Usage
import Redis from "ioredis";
const redis = new Redis(); // localhost:6379
// or: new Redis("redis://user:pass@host:6379/0")
// Strings
await redis.set("greeting", "Hello, World!");
const value = await redis.get("greeting");
console.log(value); // Hello, World!
// With expiration
await redis.set("session:abc", JSON.stringify({ userId: 1 }), "EX", 3600);
Hashes
// Store user object
await redis.hset("user:1", { name: "Alex", email: "alex@example.com", role: "admin" });
const user = await redis.hgetall("user:1");
console.log(user); // { name: "Alex", email: "alex@example.com", role: "admin" }
const name = await redis.hget("user:1", "name");
Lists and Sets
// Queue (list)
await redis.lpush("jobs", "job1", "job2", "job3");
const job = await redis.rpop("jobs"); // FIFO
// Sorted set (leaderboard)
await redis.zadd("scores", 100, "alice", 200, "bob", 150, "charlie");
const top = await redis.zrevrange("scores", 0, 2, "WITHSCORES");
console.log(top); // ["bob", "200", "charlie", "150", "alice", "100"]
Pipelining
const pipeline = redis.pipeline();
for (let i = 0; i < 1000; i++) {
pipeline.set(`key:${i}`, `value:${i}`);
}
const results = await pipeline.exec(); // Single round-trip
Pub/Sub
const subscriber = new Redis();
const publisher = new Redis();
subscriber.subscribe("notifications", (err, count) => {
console.log(`Subscribed to ${count} channels`);
});
subscriber.on("message", (channel, message) => {
console.log(`${channel}: ${message}`);
});
await publisher.publish("notifications", JSON.stringify({ type: "alert", text: "New order!" }));
Streams
// Add to stream
await redis.xadd("events", "*", "type", "page_view", "url", "/home");
await redis.xadd("events", "*", "type", "click", "button", "signup");
// Read from stream
const entries = await redis.xrange("events", "-", "+", "COUNT", 10);
entries.forEach(([id, fields]) => console.log(id, fields));
Need to extract or automate web content at scale? Check out my web scraping tools on Apify — no coding required. Or email me at spinov001@gmail.com for custom solutions.
Top comments (0)