redis / node-redis

Redis Node.js client
https://redis.js.org/
MIT License
16.92k stars 1.89k forks source link

what is the right syntax for node-redis PUBSUB CHANNELS #2589

Open halilulker opened 1 year ago

halilulker commented 1 year ago

Description

await redis.sendCommand(('PUBSUB CHANNELS', []), function(err,result){
    console.log(err);
    console.log(result);
  });

I try like this but no message in console. When I try redis-cli console its working but I dont find right syntax in nodejs.

leibale commented 1 year ago

Hi,

There are a few problems with your code:

  1. You are mixing Promises (await) and callbacks (the function you send as a second argument). See here for more details.
  2. The parentheses around ('PUBSUB CHANNELS', []) means that the 'PUBSUB CHANNELS' will be ignored, and only the empty array and the callback function will be passed to the sendCommand function:
    
    function func() {
    console.log(arguments);
    }

func((1, 2), 3); // This will log [2, 3] and ignore 1

3. You are sending `PUBSUB CHANNELS` as one argument instead of two (it should be `['PUBSUB', 'CHANNELS']`, not `['PUBSUB CHANNELS']`).

If you want to use the `.sendCommand` command to use the commands "as-is" do:
```javascript
const result = await redis.sendCommand(['PUBSUB', 'CHANNELS']);

Or, if you want to use a "type-safe" more "JavaScript friendly" API (which is probably what your are looking for):

const result = await client.PUBSUB_CHANNELS();
// or
const result = await client.pubSubChannels();