schat2-clive/assets/countries.js

64 lines
1.6 KiB
JavaScript
Raw Normal View History

2022-11-02 05:16:17 +00:00
'use strict';
const fs = require('fs').promises;
const crypto = require('crypto');
2022-11-06 01:06:04 +00:00
const { argv } = require('yargs');
// const bhttp = require('bhttp');
const countries = require('./countries.json');
2022-11-06 01:06:04 +00:00
const states = require('./states-us.json');
2022-11-06 15:14:14 +00:00
const data = {
countries,
states,
flags: countries,
};
2022-11-02 05:16:17 +00:00
/*
async function fetchCountries() {
const res = await bhttp.get('http://localhost:3000/api/countries');
if (res.statusCode === 200) {
await fs.writeFile('./assets/countries.json', JSON.stringify(res.body, null, 4));
console.log('Done fetching countries!');
return;
}
console.log(`Failed to fetch countries: ${res.statusCode}`);
}
*/
2022-11-02 05:16:17 +00:00
async function init() {
2022-11-06 15:14:14 +00:00
const type = argv.type || 'countries';
2022-11-06 01:06:04 +00:00
const countryImgs = await fs.readdir(`./assets/${type}`);
const countriesByCode = Object.fromEntries(data[type].map((country) => [country.alpha2, country]));
2022-11-02 05:16:17 +00:00
2022-11-17 21:05:05 +00:00
const imgCountries = await Promise.all(countryImgs.filter((file) => !['encoded', 'disabled'].includes(file)).map(async (file) => {
2022-11-06 15:14:14 +00:00
const code = file.match(/(\w+).png/)?.[1];
if (!code || !countriesByCode[code]) {
2022-11-17 21:05:05 +00:00
console.warn(`No country for ${file} with code ${code}`);
2022-11-06 15:14:14 +00:00
return null;
}
const filename = `${crypto.createHash('md5').update(code).digest('hex').slice(0, 4)}.png`;
2022-11-02 05:16:17 +00:00
2022-11-06 01:06:04 +00:00
await fs.copyFile(`./assets/${type}/${file}`, `./assets/${type}/encoded/${filename}`);
2022-11-02 05:16:17 +00:00
return {
file: filename,
code,
...countriesByCode[code],
};
2022-11-17 21:05:05 +00:00
}));
2022-11-02 05:16:17 +00:00
2022-11-17 21:05:05 +00:00
await fs.writeFile(`./assets/${type}-curated.json`, JSON.stringify(imgCountries.filter(Boolean), null, 4));
2022-11-02 05:16:17 +00:00
console.log('Done!');
}
init();
// fetchCountries();