Delete all Redis keys (with prefix) in Node.js

Redis is simple key-value distributed in-memory database. There are several basic operations (a.k.a. commands) that you can perform, such us: SET, GET, EXPIRE, DEL, KEYS, etc.

You can delete only one key using DEL command or drop whole database using FLUSHALL (or FLUSHDB for single instance).

There is possibility to list all database keys matching the pattern by using KEYS command

Time complexity: O(N) with N being the number of keys in the database, under the assumption that the key names in the database and the given pattern have limited length.

Supported glob-style patterns:

  1. h?llo matches hello, hallo and hxllo
  2. h*llo matches hllo and heeeello
  3. h[ae]llo matches

    hello and hallo, but not hillo

This enables way to delete all keys matching pattern. From command line just run:

redis-cli KEYS "PREFIX*" | xargs redis-cli DEL

I’m using Node.js library node_redis to connect and manipulate Redis. The library contains Javascript methods equivalent to native commands.

Establishing the connection is simple:

var libredis = require('redis')
var redis = libredis.createClient(port, host, options)
 
redis.auth(pass, function() {
	// done...
});

You can simply call methods names from native commands, such us:

redis.del('SampleKey')

You can also select KEYS:

redis.keys("SampleKeyStartsWith*", function(err, rows) {
	// rows contains strings
}

So you can simply extend the functionaity of del method by adding delWildcard method into RedisClient prototype:

First approach:

redisUtils.js:

var redis = require('redis')
 
redis.RedisClient.prototype.delWildcard = function(key, callback) {
	var redis = this
 
	redis.keys(key, function(err, rows) {
		for(var i = 0, j = rows.length; i < j; ++i) {
			redis.del(rows[i])
		}
 
		return callback();
	});
}

In this code there is an issue, that callback is fired after loop iteration, not if all del’s has been performed.

Second approach:

Let’s use async module and each() method that iterates over collection and make callback in parallel, but when all has been done, final callback is fired:

redisUtils.js:

redis.RedisClient.prototype.delWildcard = function(key, callback) {
	var redis = this
 
	redis.keys(key, function(err, rows) {
		async.each(rows, function(row, callbackDelete) {
			redis.del(row, callbackDelete)
		}, callback)
	});
}

Usage:

Just include redisUtils.js and use:

require('redisUtils.js')
redis.delWildcard("SampleKeyStartsWith*", function() <a href="https://www.acheterviagrafr24.com/prix-du-viagra/">https://www.acheterviagrafr24.com/prix-du-viagra/</a> {
	// done...
}

Hope it helped.