UnlyEd/iso3166-1

View on GitHub
bin/generate

Summary

Maintainability
Test Coverage
#!/usr/bin/env node

// ISO 3166-1 database generator tool

// The MIT License (MIT)

// Copyright (c) 2015 Michael Scott Hertzberg

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

const csv2 = require('csv2')
const es = require('event-stream')
const fs = require('fs')
const hyperquest = require('hyperquest')
const json = require('jsonstream2')
const path = require('path')
const size = require('file-size')
const through2 = require('through2')

const countries = []

hyperquest('https://raw.githubusercontent.com/datasets/country-codes/master/data/country-codes.csv')
  .pipe(csv2())
  .pipe(through2.obj(function (chunk, _, cb) {
    this.push({ alpha2: chunk[9], alpha3: chunk[2] })
    cb()
  }))
  .on('data', (data) => {
    if (data.alpha2.length === 2 && data.alpha3.length === 3) {
      countries.push(data)
    }
  })
  .on('end', () => {
    const outputJson = path.join(__dirname, '../', 'data/countries.json')
    es.readArray(countries)
      .pipe(json.stringify())
      .pipe(fs.createWriteStream(outputJson))
      .on('finish', () => {
        console.log(`OK. Built ${outputJson} - ${size(fs.statSync(outputJson).size).human('SI')}`)
      })
  })