Skip to content

Instantly share code, notes, and snippets.

@swingley
Last active May 26, 2020 02:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swingley/968f2d42cff45e087175908a86582192 to your computer and use it in GitHub Desktop.
Save swingley/968f2d42cff45e087175908a86582192 to your computer and use it in GitHub Desktop.
const fs = require('fs')
const path = require('path')
const axios = require('axios')
const API_KEY = 'signupforafreeapikeyandaddithere'
const BASE_URL = 'https://api.census.gov/data/2010/dec/sf1'
const states = `${BASE_URL}?get=NAME&for=state:*&key=${API_KEY}`
const counties = `${BASE_URL}?get=NAME&for=county:*&key=${API_KEY}`
const DATA_DIR = 'data'
const API_RESPONSE_FILE_PREFIX = 'census_api_response'
const STATES_FILE = path.join(DATA_DIR, `${API_RESPONSE_FILE_PREFIX}_fips_states.json`)
const COUNTIES_FILE = path.join(DATA_DIR, `${API_RESPONSE_FILE_PREFIX}_fips_counties.json`)
const responsesExist = () => {
let filesExist = false
if (fs.existsSync(STATES_FILE)) {
filesExist = true
}
if (fs.existsSync(COUNTIES_FILE)) {
filesExist = true
}
return filesExist
}
if (!responsesExist()) {
axios.all([
axios.get(states),
axios.get(counties)
]).then(axios.spread((statesResponse, countiesResponse) => {
fs.writeFileSync(STATES_FILE, JSON.stringify(statesResponse.data, null, 2))
fs.writeFileSync(COUNTIES_FILE, JSON.stringify(countiesResponse.data, null, 2))
console.log('wrote census API responses')
})).catch(error => console.log('Error getting census api responses', error))
} else {
console.log(`responses already exist in ${DATA_DIR} dir:\n\t${STATES_FILE}\n\t${COUNTIES_FILE}`)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment