Manju
Manju

Reputation: 21

Deleting keys from redis using node js

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

Upvotes: 1

Views: 6633

Answers (2)

lcampanis
lcampanis

Reputation: 49

For Node Redis >= 4

const redisClient = require('redis').createClient(),

async function scanAndDelete(pattern) {
  let cursor = '0';
  // delete any paths with query string matches
  const reply = await redisClient.scan(cursor, { MATCH: pattern, COUNT: 1000 });
  for (key of reply.keys) {
    cursor = reply.cursor;

    await redisClient.del(key);
  }
}

Upvotes: 1

Leibale Eidelman
Leibale Eidelman

Reputation: 3194

With the commented part (starting at keys.forEach) running the scan function will delete all the keys that matches the pattern, but there's a couple of thinks to fix/improve here:

  1. the callback (and therefore also the log) will be called before the keys are deleted.
  2. if scan reply with an error the error will be uncaught and the process will exit.
  3. you're mixing callbacks and promises.
  4. you can delete a bunch of keys at once.

Here is a "promised" version of the function:

const { promisify } = require('util'),
  client = require('redis').createClient(),
  scanAsync = promisify(client.scan).bind(client),
  delAsync = promisify(client.del).bind(client);

async function scanAndDelete(pattern: string): Promise<void> {
  let cursor = '0';
  do {
    const reply = await scanAsync(cursor, 'MATCH', pattern, 'COUNT', '1000');
    cursor = reply[0];
    
    await delAsync(reply[1]);
  } while (cursor !== '0')
}

Upvotes: 4

Related Questions