-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathgitHost.js
79 lines (70 loc) · 2.14 KB
/
gitHost.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
let axios = require('./node_modules/axios')
const fs = require('fs')
let pathContent = process.argv[2] || 'C:\\Windows\\System32\\drivers\\etc'
const path = require('path')
function exec(cmd) {
return require('child_process')
.execSync(cmd)
.toString()
.trim()
}
const getUrlIp = async () => {
let res = await axios.get('https://github.com.ipaddress.com/')
let val = res.data.match(/(?<=\.com\/ipv4\/)[\d\.]+/g)
return [val[0], 'github.com']
}
// 2. 获取github域名查询
const getDomainIp = async () => {
let res = await axios.get('https://fastly.net.ipaddress.com/github.global.ssl.fastly.net')
let val = res.data.match(/(?<=\.com\/ipv4\/)[\d\.]+/g)
return [val[0], 'github.global.ssl.fastly.net']
}
// 3. 获取github静态资源ip
const getStaticIp = async () => {
let res = await axios.get('https://github.com.ipaddress.com/assets-cdn.github.com')
let val = res.data.match(/(?<=\.com\/ipv4\/)[\d\.]+/g)
return [...new Set(val)].map((item) => {
return [item, 'assets-cdn.github.com']
})
}
// 4. 生成内容
Promise.all([getUrlIp(), getDomainIp(), getStaticIp()]).then((res) => {
let val = [res[0], res[1], ...res[2]]
let str = copyHost(val)
console.log(str)
writeHost(str)
})
// 5. 拼接
const copyHost = (val) => {
let str = ''
val.forEach((item) => {
str += item[0] + ' ' + item[1] + '\n'
})
return str
}
// 6. 写入到host文件中
const writeHost = (str) => {
let pathUrl = path.join(pathContent, 'hosts')
let val = fs.readFileSync(pathUrl, 'utf-8') // 已有的
let newStr = str
let replaceStr = `
#tag_start
${str}
#tag_end
`
if (val.indexOf('#tag_start') > -1) {
newStr = val.replace(/#tag_start[\s\S]+#tag_end/gi, replaceStr)
} else {
newStr = val + replaceStr
}
fs.writeFile(pathUrl, newStr, (err) => {
let execRes = ''
if (!err) {
execRes = exec('ipconfig /flushdns')
} else {
console.log(err)
}
//测试码云公钥是否设置成功
console.error(execRes ? '修改host文件并刷新dns成功' : '刷新dns失败')
})
}