Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.