id | title | sidebar_label | slug | authors | |
---|---|---|---|---|---|
index-redisandnodejs |
Using Redis with Node.js |
Redis and Node.js |
/develop/node/nodecrashcourse/redisandnodejs |
|
import Authors from '@theme/Authors';
To connect to Redis from an application, we need a Redis client library for the language that we're coding in. Redis clients perform the following functions:
- Manage the connections between our application and the Redis server.
- Handle network communications to the Redis server using Redis' wire protocol.
- Provide a language-specific API that we use in our application.
For Node.js, there are two popular Redis clients: node-redis and ioredis. Both clients expose similar programming APIs, wrapping each Redis command as a function that we can call in a Node.js script. For this course, we'll use node-redis.
Here's a complete Node.js script that uses node-redis to perform the SET and GET commands that we previously tried in redis-cli:
import { createClient } from 'redis';
// Connect to Redis at 127.0.0.1, port 6379.
const redisClient = await createClient({ url: 'redis://127.0.0.1:6379' })
.on('error', err => console.error('Redis Client Error', err))
.connect();
// Set key "myname" to have value "Simon Prickett".
await redisClient.set('myname', 'Simon Prickett');
// Get the value held at key "myname" and log it.
const value = await redisClient.get('myname');
console.log(value);
// Disconnect from Redis.
await redisClient.quit();
node-redis wraps each Redis command in a function that returns a Promise
. Here, I'm using async/await to wait for each command to be executed on the Redis server before moving on to the next.
Running this code displays the value that's now stored in Redis:
$ node basic_set_get.js
Simon Prickett
The following additional resources can help you understand how to access Redis from a Node.js application:
- node-redis: node-redis on npm.
- ioredis: ioredis on npm.
- RU102JS, Redis for JavaScript Developers: A free online course at Redis University that provides a deep dive into Redis for Node.js applications. You can expect to learn how to make connections to Redis, store and retrieve data, and leverage essential Redis features such as sorted sets and streams.
- Redis clients by programming language: A large list of Redis clients at redis.io.