const Redis = require("ioredis");
const redis = new Redis();
const pub = new Redis();

const processMessage = (message) => {
  console.log("Id: %s. Data: %O", message[0], message[1]);
};

async function listenForMessage(lastId = "$") {
  // `results` is an array, each element of which corresponds to a key.
  // Because we only listen to one key (mystream) here, `results` only contains
  // a single element. See more: https://redis.io/commands/xread#return-value
  const results = await redis.xread(
    "BLOCK",
    0,
    "STREAMS",
    "user-stream",
    lastId
  );
  const [key, messages] = results[0]; // `key` equals to "user-stream"

  messages.forEach(processMessage);

  // Pass the last id of the results to the next round.
  await listenForMessage(messages[messages.length - 1][0]);
}

listenForMessage();

setInterval(() => {
  // `redis` is in the block mode due to `redis.xread('BLOCK', ....)`,
  // so we use another connection to publish messages.
  pub.xadd("user-stream", "*", "name", "John", "age", "20");
}, 1000);

@@ -64,27 +64,79 @@
 nst 
-pub = new Redis();%0A
+sub = new Redis();%0Aconst pub = new Redis();%0A%0A// Usage 1: As message hub
 %0Acon
@@ -539,33 +539,26 @@
 ait 
-redis
+sub
 .xread(
-%0A    
 %22BLOCK%22,
 %0A   
@@ -557,19 +557,11 @@
 CK%22,
-%0A    0,%0A   
+ 0,
  %22ST
@@ -567,20 +567,16 @@
 TREAMS%22,
-%0A   
  %22user-s
@@ -586,22 +586,15 @@
 am%22,
-%0A   
  lastId
-%0A  
 );%0A 
@@ -1058,8 +1058,445 @@
  1000);%0A
+%0A// Usage 2: As a list%0Aasync function main() %7B%0A  redis%0A    .pipeline()%0A    .xadd(%22list-stream%22, %22*%22, %22id%22, %22item1%22)%0A    .xadd(%22list-stream%22, %22*%22, %22id%22, %22item2%22)%0A    .xadd(%22list-stream%22, %22*%22, %22id%22, %22item3%22)%0A    .exec();%0A%0A  const items = await redis.xrange(%22list-stream%22, %22-%22, %22+%22, %22COUNT%22, 2);%0A  console.log(items);%0A  // %5B%0A  //   %5B '1647321710097-0', %5B 'id', 'item1' %5D %5D,%0A  //   %5B '1647321710098-0', %5B 'id', 'item2' %5D %5D%0A  // %5D%0A%7D%0A%0Amain();%0A

add examples for xrange and xadd