Lists
Let's explore some techniques for working with Redis lists within Node. Instead of a list of fruits, let's work with vegetables this time:
[ , , ]
Add an Element to a List
Here's the code to add a to a Redis list with a key called veggies
:
const Redis = require('ioredis');
const redis = new Redis();
async function main() {
const key = 'veggies';
const vegetable = 'tomato';
try {
const result = await redis.rpush(key, vegetable);
console.log(result);
} catch (error) {
console.error(error);
}
redis.disconnect();
}
main();
If the rpush
command is successful in line 9, the number of items in the list (after adding the new item) is displayed in line 10.
Add Multiple Elements to a List
Let's add a JavaScript array of vegetables to our list:
const Redis = require('ioredis');
const redis = new Redis();
async function main() {
const key = 'veggies';
const veggies = ['tomato', 'corn', 'eggplant'];
try {
const result = await redis.rpush(key, ...veggies);
console.log(result);
} catch (error) {
console.error(error);
}
redis.disconnect();
}
main();
In line 8, notice that we use the JavaScript Spread syntax to expand the veggies
array into multiple arguments to be passed to the rpush
function. This enables us to push all the vegetable elements to the redis list in one operation. As a less elegant approach, we could have looped through the veggies
array, and pushed each vegetable element one-by-one.
Remove an Element from a List
Next, we remove an element from the list using rpop
:
In line 8, the rpop
command removes and returns the last element of the veggies
list, and stores it in the veggie
variable.
Return all Elements in a List
We can use the lrange
command to return a JavaScript array of elements from a list:
const Redis = require('ioredis');
const redis = new Redis();
async function main() {
const key = 'veggies';
try {
const veggies = await redis.lrange(key, 0, -1);
veggies.forEach(v => console.log(v));
} catch (error) {
console.error(error);
}
redis.disconnect();
}
main();
In line 8, we use a start
value of 0 and a stop value of -1
to return all elements in the Redis list.