Dragonfly Cloud announces new enterprise security features - learn more

Dragonfly

Redis XREAD in Node.js (Detailed Guide w/ Code Examples)

Use Case(s)

The XREAD command is used in Redis Streams when a client wants to consume data. It allows for both blocking and non-blocking reads from one or multiple streams. This is particularly useful when you need to process stream data in real-time, such as in a chat application, tracking user activity, or handling event-driven architectures.

Code Examples

Consider an application where we are using the Node Redis client library and want to read from a Redis Stream named "mystream".

  1. Blocking Read
const redis = require('redis');
const client = redis.createClient();

client.xread('BLOCK', 0, 'STREAMS', 'mystream', '$', function(err, stream) {
    if (err) throw err;
    console.log(stream);
});

In this example, we are using the BLOCK option with a timeout of 0, indicating that it will wait indefinitely for new data. The dollar sign $ indicates that we want to read any new messages that arrive after initiating this command.

  1. Non-Blocking Read
const redis = require('redis');
const client = redis.createClient();

client.xread('STREAMS', 'mystream', '0', function(err, stream) {
    if (err) throw err;
    console.log(stream);
});

In this instance, we're performing a non-blocking read. The '0' indicates that we want to start reading from the beginning of the stream.

Best Practices

Common Mistakes

FAQs

Q: Can we read from multiple streams using XREAD in Node?

Yes, you can add more stream IDs to the 'STREAMS' option like so:

client.xread('STREAMS', 'mystream1', 'mystream2', 'lastID1','lastID2', function(err, stream) {
    if (err) throw err;
    console.log(stream);
});

Was this content helpful?

Similar Code Examples

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Switch & save up to 80% 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost