Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NPM `redis` package, .exists(...) always returns true. Why?

Tags:

node.js

redis

I have a little Node.js project with Redis that is in development. What I am currently seeing is that client.exists(anything) returns true, even when that key does not exist in the Redis store. Here is some code to demonstrate what I am doing.

const key = 'k'
const content = 'blah blah'
client.rpush(key, content)

I run the above code and I stop. Now, on the command line, I do the following:

> redis-cli
:6379> exists k
true
:6379> exists foo
false

Awesome! As expected. Now, I run the following code back in Node.js:

const key = 'k'
if(client.exists(key)) console.log('should print')
if(client.exists('foo')) console.log('should not print')

Unfortunately, the result I'm getting in console output is:

should print
should not print

Why is Redis in Node.js reporting that something exists when Redis on the CLI reports, as expected, that thing does not exist?

like image 909
Steverino Avatar asked Sep 19 '25 04:09

Steverino


1 Answers

Because you're using the library wrong, as it's asynchronous.

If you read the docs, you'll find that you need to pass in a result callback (or promisify the library to use promises instead).

client.exists(key, (err, ok) => {
  if (err) throw err;
  console.log(ok);
});
like image 65
AKX Avatar answered Sep 23 '25 07:09

AKX