One of the most popular libraries for working with Redis server in a Node.js application is node-redis
, which can be found at https://github.com/NodeRedis/node-redis.
To install the library in your project, run the following command:
npm install redis
Tip: If your project is brand new and does not have a
package.json
file, make sure to runnpm init -y
first.
Connecting to the Redis Instance
Once the library is installed, require it in your project using:
const redis = require('redis')
or
import redis from 'redis'
After you have the redis
object, create a new client using:
const client = redis.createClient({
url: 'redis://YOUR REDIS INSTANCE URL'
})
and connect to the Redis server using (inside an async function):
await client.connect()
Once you have the client, you can perform all the operations that Redis provides.
To close the connection, simply call:
client.quit()
Storing and Retrieving Key-Value Pairs
To store a key-value pair in Redis, use the set()
method:
client.set("<key>", "<value>")
For example:
client.set("name", "Flavio")
client.set("age", 37)
If you run KEYS *
in redis-cli
on a clean Redis server, you will see the two keys appearing:
To retrieve the value stored in a key, use the get()
method:
const value = await client.get("name")
To delete a key-value pair, use the del()
method:
client.del("names")
Working with Lists
In Redis, you can work with lists using the following commands provided by the client
object:
lPush
rPush
lTrim
lRange
To create a list, use the lPush()
method:
client.lPush('names', 'Flavio')
To push a new item to the bottom of the list, use the rPush()
method:
client.rPush('names', 'Roger')
To add an item at the top of the list, use the lPush()
method:
client.lPush('names', 'Syd')
To list all the items in a list, use the lRange()
method:
const result = await client.lRange('names', 0, -1)
// result is [ 'Roger', 'Flavio', 'Syd' ]
To drop items from a list, use the rPop()
method:
client.rPop('names')
To delete a list, use the del()
method:
client.del('names')
Working with Sets
In Redis, you can work with sets using the following commands provided by the client
object:
sAdd
sPop
sMembers
.
To create a set, use the sAdd()
method:
client.sAdd('names', 'Flavio')
To add more items to the set, use the sAdd()
method:
client.sAdd('names', 'Roger')
You can add multiple items at once using the sAdd()
method:
client.sAdd('names', 'Roger', 'Syd')
You can also pass an array to add multiple items:
const names = ['Flavio', 'Roger', 'Syd']
client.sAdd('names', names)
To list all the items in a set, use the sMembers()
method:
const names = await client.sMembers('names')
To drop a random item from a set, use the sPop()
method:
client.sPop('names')
You can add a second parameter to drop multiple random items:
client.sPop('names', 3)
To delete a set, use the del()
method:
client.del('names')
Working with Hashes
In Redis, you can work with hashes using the following commands provided by the client
object:
hSet
hGetAll
hSet
hIncrBy
To create a hash, use the hSet()
method:
client.hSet('person:1', 'name', 'Flavio', 'age', 37)
To get all the properties of a user, use the hGetAll()
method:
const items = client.hGetAll('person:1')
To update a hash property, use the hSet()
method:
client.hSet('person:1', 'age', 38)
To increment a value stored in a hash, use the hIncrBy()
method:
client.hIncrBy('person:1', 'age', 1)
To delete a hash, use the del()
method:
client.del('person:1')
Subscriptions
Subscriptions are an amazing feature of Redis that allow us to do really fancy things in Node.js.
A publisher sends a message on a channel and multiple subscribers receive it.
To subscribe to a channel, use the subscribe()
method:
await subscriber.subscribe('dogs', (message) => {
console.log(message);
})
To publish a message on a channel, use the client.publish('<channel>', '<message>')
method:
client.publish('dogs', 'Roger')
Please note that you cannot publish and subscribe using the same client
instance.
To do so in the same app, create 2 clients:
const subscriber = redis.createClient({ ... })
const publisher = redis.createClient({ ... })
await subscriber.subscribe('dogs', (message) => {
console.log(channel, message);
})
publisher.publish('dogs', 'Roger')