UNPKG

js-locations

Version:

A simple Node.js library for accessing country, state, and city data.

76 lines (63 loc) 2.41 kB
const fs = require("fs"); // Function to load data from JSON file function loadData() { try { const data = fs.readFileSync("locationsData.json", "utf8"); // Replace 'data.json' with your actual file path return JSON.parse(data); } catch (error) { console.error("Error loading data:", error); return null; } } // Function to retrieve all countries function getAllCountries() { const data = loadData(); if (!data) return null; return data; } function getCountryByName(name) { const data = loadData(); if (!data) return null; return data.find( (country) => country.name.toLowerCase() === name.toLowerCase() ); } // Function to get states by country name (case-insensitive) function getStatesByCountry(countryName) { const country = getCountryByName(countryName); if (!country) return null; return country.states; } // Function to get cities by state name within a country (case-insensitive) function getCitiesByState(countryName, stateName) { const states = getStatesByCountry(countryName); if (!states) return null; const state = states.find( (state) => state.name.toLowerCase() === stateName.toLowerCase() ); if (!state) return null; return state.cities; } // Function to get phone code by country name (case-insensitive) function getPhoneCodeByCountry(countryName) { const country = getCountryByName(countryName); if (!country) return null; return country.phone_code; } // Function to get currency code by country name (case-insensitive) function getCurrencySymbolByCountry(countryName) { const country = getCountryByName(countryName); if (!country) return null; return country.currency_symbol; } // Example usage const allCountries = getAllCountries(); console.log("All countries:", allCountries); const usaData = getCountryByName("United States"); console.log("USA data:", usaData); const californiaCities = getCitiesByState("United States", "California"); console.log("California cities:", californiaCities); const canadaPhoneCode = getPhoneCodeByCountry("Canada"); console.log("Canada phone code:", canadaPhoneCode); const usaCurrencyCode = getCurrencySymbolByCountry("USA"); // USA is not a valid country name but demonstrates functionality for typos console.log("USA currency code:", usaCurrencyCode); // Outputs null since USA is not found