Dragonfly Cloud is now available in the AWS Marketplace - learn more

Node.js: Deleting Redis Cache (Detailed Guide w/ Code Examples)

Use Case(s)

In Node.js applications, you may need to delete cache stored in Redis for several reasons: expiring sessions, invalidating old data, or freeing up memory space.

Code Examples

  • Deleting a single key To remove a specific key-value pair from the Redis cache, use the del method provided by the node-redis client.
const redis = require('redis'); const client = redis.createClient(); client.del('key', function(err, response) { if (err) throw err; console.log(response); });

In this code, 'key' is the key of the item you wish to delete. The response will be the number of keys that were removed.

  • Deleting multiple keys If you need to delete multiple keys at once, you can do so by passing an array of keys to the del method.
const redis = require('redis'); const client = redis.createClient(); client.del(['key1', 'key2', 'key3'], function(err, response) { if (err) throw err; console.log(response); });

In this example, 'key1', 'key2', and 'key3' are the keys of the items you want to delete.

Best Practices

  • It's best to delete keys responsibly as accidental deletion could lead to loss of important data.
  • Try to implement error handling for better resilience.

Common Mistakes

  • Not checking if the key exists before deletion can lead to errors. Always ensure the key is present in the Redis cache before attempting to delete it.
  • Not handling exceptions may cause the application to crash if there's an error during deletion.

FAQs

  • Can I delete all keys in redis cache? Yes, you can use flushdb or flushall commands. However, be careful as these will delete everything in the selected database (flushdb) or in all databases (flushall).

Was this content helpful?

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