id | title | sidebar_label | slug | authors | ||
---|---|---|---|---|---|---|
index-gettingstarted |
Getting Started with Node and Redis |
Getting Started |
/develop/node/gettingstarted |
|
import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; import Authors from '@theme/Authors';
Find tutorials, examples and technical articles that will help you to develop with Redis and Node.js/JavaScript:
Redis is an open source, in-memory, key-value data store most commonly used as a primary database, cache, message broker, and queue. Redis cache delivers sub-millisecond response times, enabling fast and powerful real-time applications in industries such as gaming, fintech, ad-tech, social media, healthcare, and IoT.
Redis is a great database for use with Node. Both Redis and Node share similar type conventions and threading models, which makes for a very predictable development experience. By pairing Node and Redis together you can achieve a scalable and productive development platform.
Redis has two primary Node clients which are node-redis and ioredis. Both are available through npm. We generally suggest using node-redis, as it has wide support for Redis modules, is easily extended, and is widely used.
Check out a list of Redis clients that the community has built for Node here.
This article shows how to get started with the recommended libraries: node-redis and ioredis.
<Tabs defaultValue="node-redis" values={[ {label: 'node-redis', value: 'node-redis'}, {label: 'ioredis', value: 'ioredis'}, ]}>
You can either run Redis in a Docker container or directly on your Mac OS. Use the following commands to setup a Redis server locally:
brew tap redis-stack/redis-stack
brew install --cask redis-stack
:::info INFO Redis Stack unifies and simplifies the developer experience of the leading Redis data store, modules and the capabilities they provide. Redis Stack bundles five Redis modules: RedisJSON, RedisSearch, RedisGraph, RedisTimeSeries, and RedisBloom. Learn more :::
Before we start the CLI, let's start up the Redis server: redis-server
. It should result in an output similar to the following:
90856:C 20 Apr 2023 07:05:50.412 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
90856:C 20 Apr 2023 07:05:50.412 # Redis version=6.2.11, bits=64, commit=720ea82e, modified=0, pid=90856, just started
90856:C 20 Apr 2023 07:05:50.412 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
90856:M 20 Apr 2023 07:05:50.412 * Increased maximum number of open files to 10032 (it was originally set to 256).
90856:M 20 Apr 2023 07:05:50.412 * monotonic clock: POSIX clock_gettime
_._
_.-``__ ''-._
_.-`` `. `_. ''-._ Redis 6.2.11 (720ea82e/0) 64 bit
.-`` .-```. ```\/ _.,_ ''-._
( ' , .-` | `, ) Running in standalone mode
|`-._`-...-` __...-.``-._|'` _.-'| Port: 6379
| `-._ `._ / _.-' | PID: 90856
`-._ `-._ `-./ _.-' _.-'
|`-._`-._ `-.__.-' _.-'_.-'|
| `-._`-._ _.-'_.-' | https://redis.io
`-._ `-._`-.__.-'_.-' _.-'
|`-._`-._ `-.__.-' _.-'_.-'|
| `-._`-._ _.-'_.-' |
`-._ `-._`-.__.-'_.-' _.-'
`-._ `-.__.-' _.-'
`-._ _.-'
`-.__.-'
90856:M 20 Apr 2023 07:05:50.413 # Server initialized
90856:M 20 Apr 2023 07:05:50.414 * Ready to accept connections
Now, in a separate terminal instance (we need to leave the Redis server running), ensure that you are able to use the following Redis command to connect to the Redis instance.
redis-cli
127.0.0.1:6379>
Now you should be able to perform CRUD operations with Redis keys. The above Redis client command might require password if you have setup authentication in your Redis configuration file. Refer Redis Command Reference
Run the following NPM command to install the Redis client.
npm install redis
Use the following sample code for our Node.js application:
import { createClient } from 'redis';
async function nodeRedisDemo() {
try {
const client = createClient();
await client.connect();
await client.set('mykey', 'Hello from node redis');
const myKeyValue = await client.get('mykey');
console.log(myKeyValue);
const numAdded = await client.zAdd('vehicles', [
{
score: 4,
value: 'car',
},
{
score: 2,
value: 'bike',
},
]);
console.log(`Added ${numAdded} items.`);
for await (const { score, value } of client.zScanIterator('vehicles')) {
console.log(`${value} -> ${score}`);
}
await client.quit();
} catch (e) {
console.error(e);
}
}
nodeRedisDemo();
npm install ioredis
const Redis = require('ioredis');
async function ioredisDemo() {
try {
const client = new Redis();
await client.set('mykey', 'Hello from io-redis!');
const myKeyValue = await client.get('mykey');
console.log(myKeyValue);
const numAdded = await client.zadd('vehicles', 4, 'car', 2, 'bike');
console.log(`Added ${numAdded} items.`);
const stream = client.zscanStream('vehicles');
stream.on('data', (items) => {
// items = array of value, score, value, score...
for (let n = 0; n < items.length; n += 2) {
console.log(`${items[n]} -> ${items[n + 1]}`);
}
});
stream.on('end', async () => {
await client.quit();
});
} catch (e) {
console.error(e);
}
}
ioredisDemo();
Redis Launchpad is like an “App Store” for Redis sample apps. You can easily find apps for your preferred frameworks and languages. Check out a few of these apps below, or click here to access the complete list.
A Hacker News Clone project built in NextJS, NodeJS and Express based on RediSearch & RedisJSON
Basic Redis Caching This application calls the GitHub API and caches the results into Redis.
Redis Rate-Limiting This is a very simple app that demonstrates rate-limiting feature using Redis.
Notifications with WebSocket, Vue & Redis
This project allows you to push notifications in a Vue application from a Redis PUBLISH
using WebSockets.
Redis Rapid Tips: ioredis (YouTube)
Mapping Objects between Node and Redis (YouTube)
Build full-fledged Redis applications with Node.js and Express.