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:
For Node.js, there are two popular Redis clients: ioredis and node_redis. 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 ioredis which has built in support for modern JavaScript features such as Promises.
Here's a complete Node.js script that uses ioredis to perform the SET and GET commands that we previously tried in redis-cli:
const Redis = require('ioredis');
const redisDemo = async () => {
// Connect to Redis at 127.0.0.1, port 6379.
const redisClient = new Redis({
host: '127.0.0.1',
port: 6379,
});
// 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.
redisClient.quit();
};
redisDemo();
ioredis wraps each Redis command in a function that can either accept a callback or return 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:
In this video, I take a look at how to get up and running with the ioredis client: