This repository has been archived by the owner on Apr 13, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·108 lines (88 loc) · 2.65 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#!/usr/bin/env node
const program = require('commander');
const Redis = require('ioredis');
const package = require('./package.json');
program
.version(package.version)
.description(package.description)
.option('--rm', 'Remove matching keys')
.option('-c, --cluster')
.option('-r, --host [host]', 'host', '127.0.0.1')
.option('-p, --port [port]', 'port', '6379')
.option('-k, --match [match]', 'hash keys regex to scan for')
.option('-f, --fieldMatch [fieldMatch]', 'hash field regex to scan for');
program.on('--help', () => {
console.log(' Examples:');
console.log('');
console.log(' $ redisHashScan -cr 192.168.99.100 -k updates:* -f file:*');
console.log('');
});
program.parse(process.argv);
const scan = async (cluster, host, port, match, fieldMatch, remove) => {
let redis;
if (cluster) {
console.log('Connecting to Cluster');
redis = new Redis.Cluster([{port: port, host: host}]);
} else {
console.log('Connecting to Redis');
redis = new Redis(port, host);
}
// console.log(await redis.info());
let masters;
if (cluster) {
// Get Masters
masters = redis.nodes('master');
} else {
masters = [redis];
}
const streamOpts = {};
if (match) {
streamOpts.match = match;
}
const hstreamOpts = {};
if (fieldMatch) {
hstreamOpts.match = fieldMatch;
}
// Scan all masters
Promise.all(
masters.map((node) => {
const stream = node.scanStream(streamOpts);
return new Promise( async (resolve, reject) => {
stream.on('data', async (keys) => {
const hashs = [];
for (let i in keys) {
let type = await redis.type(keys[i]);
if (type == 'hash') {
hashs.push(keys[i]);
}
}
if (hashs.length == 0) {
return;
}
await Promise.all(hashs.map((hash) => {
const hstream = node.hscanStream(hash, hstreamOpts);
return new Promise( async (hresolve, hreject) => {
hstream.on('data', async ([field, value]) => {
if (!field) {
return
}
console.log(`Found ${hash} - ${field} - ${value}`);
if (remove) {
console.log(`Removing ${hash} - ${field}`);
console.log(await redis.hdel(hash, field));
}
});
hstream.on('error', hreject);
hstream.on('end', hresolve);
});
}));
});
stream.on('error', reject);
stream.on('end', resolve);
});
})).then(() => {
console.log('Done');
redis.quit();
});
}
scan(program.cluster, program.host, program.port, program.match, program.fieldMatch);