aboutsummaryrefslogtreecommitdiff
path: root/scripts/download-country-names.js
blob: 937fb22f04a789031d20a192f402f064bcc53d39 (plain) (blame)
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
/* eslint-disable no-console */

import path from 'node:path';
import chalk from 'chalk';
import fs from 'fs-extra';
import https from 'https';

const src = path.resolve(process.cwd(), 'src/lang');
const dest = path.resolve(process.cwd(), 'public/intl/country');
const files = fs.readdirSync(src);

const getUrl = locale =>
  `https://raw.githubusercontent.com/umpirsky/country-list/master/data/${locale}/country.json`;

const asyncForEach = async (array, callback) => {
  for (let index = 0; index < array.length; index++) {
    await callback(array[index], index, array);
  }
};

const downloadFile = (url, filepath) =>
  new Promise(resolve => {
    https
      .get(url, res => {
        if (res.statusCode === 200) {
          const fileStream = fs.createWriteStream(filepath);
          res.pipe(fileStream);
          fileStream.on('finish', () => {
            fileStream.close();
            console.log('Downloaded', chalk.greenBright('->'), filepath);
            resolve();
          });
        } else {
          res.resume();
          console.warn(`Warning: ${url} returned ${res.statusCode}`);
          resolve();
        }
      })
      .on('error', err => {
        console.error(`Error downloading ${url}:`, err.message);
        resolve();
      });
  });

const download = async files => {
  await fs.ensureDir(dest);

  await asyncForEach(files, async file => {
    const locale = file.replace('-', '_').replace('.json', '');

    const filename = path.join(dest, file);
    if (!fs.existsSync(filename)) {
      const url = getUrl(locale);
      await downloadFile(url, filename);
    }
  });
};

download(files);