-
Notifications
You must be signed in to change notification settings - Fork 17
/
index.js
71 lines (64 loc) · 1.78 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
import dns from "dns";
import fs from "fs";
import { urls } from "./constants.js";
const retry = async (fn, n) => {
for (let i = 0; i < n; i++) {
try {
return await fn();
} catch {}
}
return {
failed: true,
};
};
const getHostConfig = async (url) => {
const getConfig = async () => {
const response = await dns.promises.lookup(url);
return { url, ip: response.address };
};
try {
const config = await retry(getConfig, 3);
if (config.failed) {
return { url, ip: "" };
}
return config;
} catch {}
};
const resolveUrls = async () => {
const promises = urls.map(getHostConfig);
return Promise.all(promises);
};
const generateHosts = (configs) => {
let hostStr = "# Generated by Github Hosts start \n\n";
configs.forEach((i) => {
const whiteLen = 16 - i.ip.length;
if (!i.ip) {
hostStr += `# ${i.url} update failed\n`;
} else {
hostStr += `${i.ip} ${" ".repeat(whiteLen)} ${i.url}\n`;
}
});
const updateTime = new Date().toLocaleString("en-US", {
timeZone: "Asia/shanghai",
});
hostStr += `\n# Last update: ${updateTime}\n`;
hostStr += "# Please star: https://github.com/fliu2476/gh-hosts.git\n";
hostStr += "# Generated by Github Hosts end";
return {
hostStr,
updateTime,
};
};
const writeHosts = (hosts) => {
const { hostStr, updateTime } = generateHosts(hosts);
const template = fs.readFileSync("./README.template.md", "utf-8");
const nextReadme = template.toString().replace("{{hosts}}", hostStr).replace("{{last_update_time}}", updateTime);
fs.writeFileSync("./hosts", hostStr);
fs.writeFileSync("./README.md", nextReadme);
fs.writeFileSync("./README-ZH_CN.md", nextReadme);
};
const main = async () => {
const configs = await resolveUrls();
writeHosts(configs);
};
main();