How to cache JSON data in Redis with NodeJS

Node.js has become incredibly popular for both web and mobile application development. It is a runtime for JavaScript so it can run JavaScript code on the machine. Node.js can be installed on MacOS, Linux and Windows system. The Node Package Manager (npm) enables developers to reuse useful codes which are tried and tested and helps you to build strong and steady applications quickly.

Node.js is a fast web framework, but adding the power, speed and flexibility of Redis can take it to the next level.Redis is best suited to situations that require data to be retrieved and delivered to the client as quickly as possible If you’re using Node, you can use the node-redis module to interact with Redis. If you’re using RediJSON, you can use redis-rejson module to interact with RedisJSON.

The 'ReJSON Module plugin for node_redis' package allows node_redis (2.8+) to interface with the Redis module ReJSON.To use this module, you will need Redis 4.0 or higher and the rejson module installed.

Follow the below steps to get started with RedisJSON and Node.js:

Step 1. Run RedisMod Docker container#

This simple container image bundles together the latest stable releases of Redis and select Redis modules from Redis Lab.

docker run -d -p 6379:6379 redislabs/redismod:latest

Step 2. Install Node#

brew install node

Step 3. Install Redis#

Node Redis is a high performance Node.js Redis client.

npm install redis

Step 4. Install RedisJSON#

npm -i redis-rejson

Step 5. Create a file#

Copy the below content and save the file as “app.js”

const redis=require("redis");
rejson = require('redis-rejson');
rejson(redis); /* important - this must come BEFORE creating the client */
let client= redis.createClient({
let test_node_key = 'test_node';
client.json_set(test_node_key, '.', '{"node":4303}', function (err) {
if (err) { throw err; }
console.log('Set JSON at key ' + test_node_key + '.');
client.json_get(test_node_key, '.node', function (err, value) {
if (err) { throw err; }
console.log('value of node:', value); //outputs 4303

Step 6. Run the app#

node app.js
Set JSON at key test_node.
value of node: 4303
% redis-cli> monitor
1628071593.564178 [0] "info"
1628071593.567058 [0] "json.set" "test_node" "." "{\"node\":4303}"
1628071593.572035 [0] "json.get" "test_node" ".node"