Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Node.js 5-Minute Guide: Connect to Redis and Execute Read/Write Operations

Tech 2

Redis Fundamentals

Redis is an in-memory data storage system, delivering far faster read and write performance then traditional disk-based databases. While it does not persist data by default (though optional persistence mechanisms exist), it is ideal for ephemeral use cases like tracking user session states, where temporary data loss has minimal impact.

Install Redis

For Windows users, download the official Redis installer from https://github.com/tporadowski/redis/releases. Run the .msi package, and ensure the option to add Redis to your system's global PATH is selected during setup. Verify your installation by opening a terminal and running redis-cli — a successful launch will open the interactive Redis shell, using the default host 127.0.0.1 and port 6379.

Basic Redis CLI Commansd

Write Data

Use the SET command to store a key-value pair:

SET <key> <value>

For example, SET username alice will return OK if the write succeeds.

Read Data

Retrieve stored values with the GET command:

GET <key>

This will return the stored value, or nil if no matching key exists.

List All Keys

View all existing keys in the current database with:

KEYS *

Delete Data

Remove a key-value pair using the DEL command:

DEL <key>

Node.js Integration

Initialize Project

Create a new Node.js project with default settings:

npm init -y

Install Redis Client Package

Install the latest stable Redis npm package:

npm install redis

To install the legacy v2.8.x branch (used in older projects):

npm install redis@2.8

Connnect to Redis

Legacy v2.8 Syntax

const redis = require('redis');
const redisClient = redis.createClient(6379, '127.0.0.1');

redisClient.on('error', (err) => {
  console.error('Redis client error:', err);
});

Modern v4+ Syntax

v4 uses a promise-based connection model with simplified setup:

const redis = require('redis');
const redisClient = redis.createClient();

redisClient.on('error', (err) => {
  console.error('Redis client error:', err);
});

redisClient.connect(6379, '127.0.0.1');

Write Data to Redis

Legacy v2.8 Syntax

redisClient.set('username', 'alice', redis.print);

The optional redis.print third parameter logs the operation result to the console, such as Reply: OK on success.

Modern v4+ Syntax

Use promise chains or async/await for cleaner code:

// Promise chain approach
redisClient.connect(6379, '127.0.0.1')
  .then(() => redisClient.set('username', 'alice'))
  .then((result) => console.log('Set operation result:', result))
  .catch((err) => console.error('Write failed:', err));

// Async/await approach
async function writeRedisData() {
  await redisClient.connect(6379, '127.0.0.1');
  await redisClient.set('username', 'alice');
  console.log('Data written successfully');
}
writeRedisData();

Read Data from Redis

Legacy v2.8 Syntax

Uses a callback-based API:

redisClient.get('username', (err, fetchedValue) => {
  if (err) {
    console.error('Read failed:', err);
    return;
  }
  console.log('Fetched user value:', fetchedValue);
});

Modern v4+ Syntax

Promise-based read operations:

async function readRedisData() {
  await redisClient.connect(6379, '127.0.0.1');
  const fetchedValue = await redisClient.get('username');
  console.log('Fetched user value:', fetchedValue);
}
readRedisData();

Delete Redis Data

Legacy v2.8 Syntax

redisClient.del('username', (err, deletedCount) => {
  if (err) {
    console.error('Delete failed:', err);
    return;
  }
  console.log(`Deleted ${deletedCount} key(s)`);
});

Modern v4+ Syntax

async function deleteRedisKey() {
  await redisClient.connect(6379, '127.0.0.1');
  const deletedCount = await redisClient.del('username');
  console.log(`Deleted ${deletedCount} key(s)`);
}
deleteRedisKey();

Close Redis Connection

Both legacy and modern versions use the same quit() method to terminate the connection:

redisClient.quit();

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.