-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
66 lines (50 loc) · 1.41 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
const fs = require('fs');
const isWSL = require('is-wsl');
const PATH_TO_HOSTS = isWSL ? '/mnt/c/Windows/System32/drivers/etc/hosts' : 'hosts';
const BLACKHOLE_IP = '0.0.0.0';
const DOMAIN_IP_SEPARATOR = '\t';
const LINE_SEPARATOR = isWSL ? '\r\n' : '\n';
function domainSort(a, b) {
for (let i = 0; i < Math.max(a.length, b.length); i += 1) {
if (!b[i] || a[i] > b[i]) {
return 1;
} else if (!a[i] || a[i] < b[i]) {
return -1;
}
}
return 0;
}
function domainExplode(line) {
const domain = line.split(DOMAIN_IP_SEPARATOR)[1] || '';
return domain.split('.').reverse();
}
function domainCollapse(domain) {
return BLACKHOLE_IP + DOMAIN_IP_SEPARATOR + domain.reverse().join('.');
}
fs.readFile(PATH_TO_HOSTS, function (e, hosts) {
if (e) {
console.error(e);
return process.exit(1);
}
const lines = hosts.toString().split(LINE_SEPARATOR);
const seen = {};
const special = [];
lines.forEach(function (line) {
if (line.substring(0, 7) === BLACKHOLE_IP) {
seen[line] = true;
} else if (line) {
special.push(line);
}
});
// Let's add one blank line between the comment section and the domains
special.push('');
const domains = Object.keys(seen).map(domainExplode);
domains.sort(domainSort);
const output = special.concat(domains.map(domainCollapse)).join('\n') + '\n';
fs.writeFile('./hosts', output, function (e) {
if (e) {
console.error(e);
return process.exit(1);
}
});
});