Step 1. Run a Redis server
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
Redis Stack unifies and simplifies the developer experience of the leading Redis data store, modules and the capabilities they provide. Redis Stack supports the folliwng in additon to Redis: JSON, Search, Time Series, Triggers and Functions, and Probilistic data structures.
Ensure that you are able to use the following Redis command to connect to the Redis instance.
redis-cli
localhost>
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
Step 2. Install node redis using NPM
(or YARN
)
Run the following NPM command to install the Redis client.
npm install redis
Step 2. Write your Application Code
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();