-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·80 lines (64 loc) · 1.73 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
'use strict'
const fs = require('fs')
const promisify = require('pify')
const readFile = promisify(fs.readFile)
const writeFile = promisify(fs.writeFile)
const WINDOWS = process.platform === 'win32'
const EOL = WINDOWS ? '\r\n' : '\n'
const HOSTS_FILE = WINDOWS
? 'C:/Windows/System32/drivers/etc/hosts'
: '/etc/hosts'
function fsReplaceHost(host, op) {
return readFile(HOSTS_FILE)
.then((content) => {
return replaceHost(content.toString(), host, op)
})
.then((content) => {
return writeFile(HOSTS_FILE, content)
})
.catch((err) => {
console.log(err)
})
}
function replaceHost(content, host, op) {
return new Promise((resolve, reject) => {
op = op || 'toggle'
if (['block', 'allow', 'toggle'].indexOf(op) < 0) {
reject(`Unknown operation ${op}`)
}
let lineReg = new RegExp(`^[#]?[0-9\\.\\s]*${host}$`, 'm');
let match = content.match(lineReg)
if (match) {
if (op === 'toggle') {
if(match[0][0] === '#') {
op = 'block'
} else {
op = 'allow'
}
}
if (op === 'block') {
let reg = new RegExp(`^#[0-9\\.\\s]*${host}$`, 'm')
if(reg) content = content.replace(reg, `127.0.0.1 ${host}`)
console.log(`Block ${host}`)
}
else if (op === 'allow'){
let reg = new RegExp(`^[0-9\\.\\s]*${host}$`, 'm')
if(reg) content = content.replace(reg, `#127.0.0.1 ${host}`)
console.log(`Allow ${host}`)
}
} else {
if (op === 'block' || op === 'toggle') {
content += `${EOL}127.0.0.1 ${host}`
console.log(`Block new ${host}`)
}
}
resolve(content)
})
}
module.exports = {
WINDOWS,
EOL,
HOSTS_FILE,
replaceHost,
fsReplaceHost,
}