I am trying to delete keys in redis using the below code but for some reason, its not deleting the keys in redis but consoling works perfect. Can someone please help what am I missing here
import { RedisClient } from 'redis';
let rediClient: RedisClient = redis.createClient(redisPort, redisHostName, {
auth_pass: authPass,
no_ready_check: true,
prefix: KEY_PREFIX,
retry_strategy: redisRetryStrategy,
tls: { servername: hostName },
});
let cursor = '0';
const scan = (pattern: string, callback: () => void) => {
redisClient.scan(
cursor,
'MATCH',
pattern,
'COUNT',
'1000',
async (err, reply) => {
console.log(err);
if (err) {
throw err;
}
cursor = reply[0];
const keys = reply[1];
console.log(keys);
console.log(keys.length);
console.log(keys[1]);
if (keys) {
await redisClient.del(keys[1], (deleteErr, deleteSuccess) => {
console.log(`err ==> ${deleteErr}`);
console.log(deleteSuccess);
});
console.log(` key 0 is : ${keys[0]}`);
redisClient.del(keys[0]);
// keys.forEach((key) => {
// redisClient.del(key, (deleteErr, deleteSuccess) => {
// console.log(`err ==> ${deleteErr}`);
// console.log(deleteSuccess);
// });
// });
}
if (cursor !== '0') {
console.log(cursor);
return scan(pattern, callback);
}
return callback();
}
);
};
export const deleteResetPin = (pattern: string) => {
scan(pattern, () => {
console.log('Scan Complete');
});
};
Requirement: I want to delete all keys matching the pattern using node js
2
Answers
With the commented part (starting at
keys.forEach
) running thescan
function will delete all the keys that matches the pattern, but there’s a couple of thinks to fix/improve here:Here is a "promised" version of the function:
For Node Redis >= 4