build-cidr.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. const https = require('https');
  2. const { promises: fsPromises } = require('fs');
  3. const { resolve: pathResolve } = require('path');
  4. let cidrTools;
  5. try {
  6. cidrTools = require('cidr-tools');
  7. } catch (e) {
  8. console.log('Dependency "cidr-tools" not found');
  9. console.log('"npm i cidr-tools" then try again!');
  10. process.exit(1);
  11. }
  12. (async () => {
  13. const cidr = (await get('raw.githubusercontent.com', 'misakaio/chnroutes2/master/chnroutes.txt')).split('\n');
  14. const filteredCidr = cidr.filter(line => {
  15. if (line) {
  16. return !line.startsWith('#')
  17. }
  18. return false;
  19. })
  20. return fsPromises.writeFile(pathResolve(__dirname, '../List/ip/china_ip.conf'), makeCidrList(filteredCidr), { encoding: 'utf-8' });
  21. })();
  22. function makeCidrList(cidr) {
  23. const date = new Date();
  24. return `############################
  25. # Mainland China IPv4 CIDR
  26. # Data from vx.link (tmplink @ GitHub)
  27. # Last Updated: ${date.getFullYear()}-${date.getUTCMonth() + 1}-${date.getUTCDate()} ${date.getUTCHours()}:${date.getUTCMinutes()}:${date.getUTCSeconds()}
  28. # Routes: ${cidr.length}
  29. ############################\n` + cidr.map(i => `IP-CIDR,${i}`).join('\n') + '\n########### END ############\n';
  30. };
  31. function get(hostname, path) {
  32. return new Promise((resolve, reject) => {
  33. const req = https.request(
  34. {
  35. hostname,
  36. path,
  37. method: 'GET',
  38. },
  39. (res) => {
  40. const body = [];
  41. res.on('data', (chunk) => {
  42. body.push(chunk);
  43. });
  44. res.on('end', () => {
  45. try {
  46. resolve(String(Buffer.concat(body)));
  47. } catch (e) {
  48. reject(e);
  49. }
  50. });
  51. req.on('error', (err) => {
  52. reject(err);
  53. });
  54. }
  55. );
  56. req.end();
  57. });
  58. }