1 Star 0 Fork 59

VectorTree/github-hosts

forked from fliu2476/github-hosts 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
index.js 1.74 KB
一键复制 编辑 原始数据 按行查看 历史
fliu2476 提交于 2021-12-03 17:21 . update readme.md automatic
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 hosts-generator 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 hosts-generator 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);
};
const main = async () => {
const configs = await resolveUrls();
writeHosts(configs);
};
main();
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/AllocateMyAddress/github-hosts.git
git@gitee.com:AllocateMyAddress/github-hosts.git
AllocateMyAddress
github-hosts
github-hosts
main

搜索帮助