Dragonfly Cloud announces new enterprise security features - learn more

Dragonfly

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

Use Case(s)

The XADD command in Redis is used to add new entries to a stream. This is particularly common in use cases where you need to manage and process data streams; for example, in real-time analytics systems, event sourcing, or message queues.

Code Examples

Here's an example of how you can use the xadd command in Redis using Node.js:

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

client.on('connect', function() {
    console.log('Connected to Redis...');
});

let id = '*';
let field1 = 'temperature';
let value1 = '22.5';

client.xadd('sensor_data', id, field1, value1, function(err, reply) {
    if(err) {
        console.error('Error:', err);
    } else {
        console.log('Reply:', reply);
    }
});

In this example, the command xadd adds an entry to the stream named 'sensor_data'. The ID parameter is '*', which means that the ID will be auto-generated by Redis.

Best Practices

Common Mistakes

FAQs

Q1: What does the '*' mean when used as an ID in XADD command?

The '*' means that Redis will assign the ID automatically, based on the current timestamp.

Q2: Can I add multiple fields and values in a single XADD operation?

Yes, you can. The XADD command allows you to specify multiple field-value pairs.

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