iso-locale-tools
All world countries and data points about them, as well as tools for interfacing with that data.
Installation
Install with npm or yarn.
npm install iso-locale-tools
yarn add iso-locale-tools
Usage
The full JSON array of all world countries and information about them lives in src/data/countries-expanded.json
.
Each country is represented as an object.
name
common
: common name (in English)official
: officially recognized name (in English)native
: list of names in the country's recognized languages
[key: ISO_639_3]
: ISO 639-3 language code
common
: common name (in native language)official
: officially recognized name (in native language)
alternates
: array of alternate name spellings
flag
: unicode string flagcca2
: ISO 3166-1 alpha-2 codecca3
: ISO 3166-1 alpha-3 codeccn3
: ISO 3166-1 numeric codeioc
: International Olympic Committee codegovernance
isSovereign
: whether or not the country is independent (i.e. is self-governing)governingBody
: the country that governs the dependency (undefined
if isSovereign
is true)isUNMember
: whether or not the country is a member of the UN (undefined
if isSovereign
is false)isEU
: (european countries only) whether or not the country is a member of the EUisSchengen
: (european countries only) whether or not the country is a member of the Schengen AreaisEurozone
: (european countries only) whether or not the country is a part of the Eurozone, i.e. whether or not they use the Euro currency
languages
official
: an array of officially recognized languages
name
:
common
: the name of the language in Englishnative
: the name of the language in that language
iso639_3
: ISO639-3 language codebcp47
: BCP47 tagiso14924
: ISO15924 script tagiana
: array of assigned IANA tagsisExtinct
: whether or not the language is no longer spokenisSpurious
: whether or not the language is spurious, i.e. questioned if it ever existed
spoken
: list of ISO639-3 language tags of languages spoken in the country, but are not recognized as 'official' languages
geography
coordinates
: numeric coordinates of the center of the country
isLandlocked
: whether or not the country is landlocked (not bordering the ocean)capitalCity
: a list of capital citieslandArea
: size of the country in km2region
: the region the country is in (e.g. 'americas', 'europe')subregion
: the subregion of the country (e.g. carribbean
)borderCountries
: list of countries by their ISO 3166-1 alpha-3 codes that border the country
locale
ietf
: a list of IETF locale codes (e.g. en-US
)measurementSystem
: system of measurement in usedrivingSide
: driving sidehourClock
: type of clock usedtimezones
: list of tz database timezones
name
: name of timezonetype
: the type of timezone (primary or alias)linkedTo
: (if alias) the primary timezone this timezone links toutcOffset
: hours offset from UTCdstOffset
: hours offset from UTC during DST (if country doesn't observe DST, this is the same value as UTC offset)
dateFormats
: date formats for each IETF locale
- key is the IETF locale name
- value is the date format, where:
G
= eray
= yearM
= monthd
= day
weekStartsOn
: which day is the first day of the week on the calendardistanceUnit
: the unit of distance used (kilometer or mile)temperatureMeasurement
: the unit of temperature (celsius or fahrenheit)
currencies
: list of accepted currencies
name
: official currency name (in English)shortName
: the name of the currency itself (e.g. 'dollar' as opposed to 'US Dollar')iso4217
: ISO 4217 codeisoNumeric
: ISO 4217 numeric codesymbol
: unicode symbol (e.g. '$')subunit
: subunit to whole value (e.g. 'cent')subunitToUnit
: number of subunits to reach a whole unit value (e.g. 100 cents = 1 dollar)prefix
: symbol that prefixes a currency amount (e.g. '$1')suffix
: symbol that suffixes a currency amonut (e.g. '1€')decimalMark
: symbol that denotes a decimal placedecimalPlaces
: number of decimal places rounded tothousansSeparator
: symbol to denote thousands separation
tld
: list of top-level domains usedidd
: international dialing direct info
prefix
: geographical code prefix (e.g. +1 for US)suffixes
: list of suffixes assigned (e.g. 201 in US)callingCodes
: list of calling codes (combinations of the prefix and each suffix - e.g. +1201)
subdivisions
: list of ISO 3166-2 subdivisions of each country
name
: name of the subdivision in the country's recognized languages
[key: ISO_639_3]
: ISO 639-3 language code
official
: official subdivison namecommon
: locally used name variantnative
: official name in non-alphanumeric script language (e.g. arabic, cyrillic)
There is also a truncated list (src/data/countries.json
) that abbreviates and filters out certain data to reduce file size.
Full country list vs. truncated country list
Object | countries-expanded.json | countries.json |
---|
languages.official | A list of full language objects | A list of ISO639-3 language codes |
currencies | A list of full currency objects | A list of ISO4217 currency codes |
locale.timezones | A list of full timezone objects | A list of tz database timezone names |
subdivisions | A list of subdivision objects | undefined |
Note: subdivisions
is removed from countries.json
because for most countries, it's a huge list and many times isn't needed.
API
This package contains datasets for multiple different things related to world countries. The datasets can be found in src/data/
.
import {
countriesExpanded,
countries,
currencies,
languages,
timezones,
} from 'iso-locale-tools'
Types
There are several types and enumerators to assist in handling different ISO codes.
Countries
enum ISO3166_1_Alpha2 {}
ISO3166_1_Alpha2.AX
enum ISO3166_1_Alpha2ByCountry {}
ISO3166_1_Alpha2ByCountry.denmark
enum ISO3166_1_Alpha3 {}
ISO3166_1_Alpha3.ALA
enum ISO3166_1_Alpha3ByCountry {}
ISO3166_1_Alpha3ByCountry.denmark
enum ISO3166_1_NumericByCountry {}
ISO3166_1_NumericByCountry.british_virgin_islands
enum ISO3166_2 {}
ISO3166_2.BT_42
Currency
type Currency = {
name: CurrencyNamesByISO4217 | string
shortName: CurrencyNamesByISO4217
iso_4217: ISO4217
symbol: CurrencySymbolsByISO4217 | string
subunit: string | null
subunitToUnit: number | null
prefix: string | null
suffix: string | null
decimalMark: string | null
decimalPlaces: number | null
thousandsSeparator: string | null
}
enum ISO4217 {}
ISO4217.USD
enum CurrencyNamesByISO4217 {}
CurrencyNamesByISO4217.USD
enum CurrencyShortNamesByISO4217 {}
CurrencyShortNamesByISO4217.USD
enum CurrencySymbolsByISO4217 {}
CurrencySymbolsByISO4217.USD
Language
type Language = {
name: {
common: string
native: string | null
alternates?: string[]
},
iso639_3: ISO639_3,
bcp47: BCP47,
iso15924: ISO15924
iana: string[]
countries?: ISO3166_1_Alpha2
isExtinct: boolean
isSpurious: boolean
}
enum ISO639_3 {}
ISO639_3.eng
enum BCP47 {}
BCP47.abq_Cyrl
enum ISO15924 {}
ISO15924.cyrl
Locale
type Locale = {
ietf: IETF[]
drivingSide: DrivingSide | DrivingSides
measurementSystem: MeasurementSystem | MeasurementSystems
hourClock: HourClock | HourClocks
timezones: Timezone[] | TZTimezones[]
dateFormats: {
[key in IETF]: string
}
weekStartsOn: WeekStartDay | WeekStartDays
distanceUnit: DistanceUnit | DistanceUnits
temperatureUnit: TemperatureUnit | TemperatureUnit
}
type DistanceUnit = "kilometer" | "mile"
enum DistanceUnits {
KM = "kilometer",
MI = "mile"
}
type TemperatureUnit = "celsius" | "fahrenheit"
enum TemperatureUnits {
C = "celsius",
F = "fahrenheit"
}
type WeekStartDay = "friday" | "saturday" | "sunday" | "monday"
enum WeekStartDays {
FRIDAY = "friday",
SATURDAY = "saturday",
SUNDAY = "sunday",
MONDAY = "monday"
}
type DrivingSide = "left" | "right"
enum DrivingSides {
LEFT = "left",
RIGHT = "right"
}
type MeasurementSystem = "metric" | "imperial"
enum MeasurementSystems {
METRIC = "metric",
IMPERIAL = "imperial"
}
type HourClock = "12hr" | "24hr" | "mixed"
enum HourClocks {
AM_PM = "12hr",
MILITARY = "24hr",
MIXED = "mixed"
}
type Timezone = {
name: Timezones
type: "canonical" | "link"
linkedTo: string | null
utcOffset: string
dstOffset: string
}
enum IETF {}
IETF.en_CA
enum TZTimezones {}
TZTimezones.windhoek
Location
type Location = {
coordinates: Coordinates
isLandlocked: boolean
borderCountries: ISO3166_1_Alpha3
capitalCity: string[]
landArea: number
region: Regions
subregion: Subregions
}
type Coordinates = {
latitude: number
longitude: number
}
enum Regions {}
Regions.oceania
enum Subregions {}
Subregions.australia_new_zealand
Utils
Countries
countryNameToKey(name: string): CountryKey
: gets the country name key for a country by it's common name (name.common
)removeDiacritics(str: string): string
: Removes diacritics (accented characters, etc.) from a string
import { countryNameToKey, removeDiacritics } from 'iso-locale-tools'
const countryKey = countryNameToKey("Svalbard and Jan Mayen")
const cca2 = ISO3166_1_Alpha2ByCountry[countryKey]
const aland = removeDiacritics("Åland Islands")
Currency
getConversionRate({ from, to }: { from: ISO4217, to: ISO4217 }): number | Error
: returns the conversion rate between 2 currencies, returns an error if one encountered. This function utilizes the free version of the currconv api.
import { getConversionRate, ISO4217 } from 'iso-locale-tools'
const conversionRate = getConversionRate({
from: ISO4217.USD,
to: ISO4217.EUR
})
Locale
convertDistance(distance: number, fromUnit: "kilometer" | "mile"): number
: converts a distance from a given unit to the opposite unitgetDateFnsLocale(locale: IETF, { fallbackLocale }: { fallbackLocale: DateFnsLocale }): DateFnsLocale
: returns a date-fns locale object. if a direct match is not found, it'll try to detect the closest locale, otherwise it uses a fallback. the default fallback is en-US
.getDatePatternForLocale(locale: IETF)
: gets the date format pattern (e.g. 'yyyy-MM-dd') for a given localegetDateTimeForTimezone({ date, dateTimeFormat, timezone, serverTimezone }: { date?: Date | number | string, dateTimeFormat: string, timezone: TZTimezone, serverTimezone?: TZTimezone }): Date
: returns a date formatted and converted to a given timezone. if date
is not provided, it fallsback to Date.now()
. serverTimezone
is the timezone to compare against, if necessary (fallback is UTC).
import {
convertDistance,
getDateFnsLocale,
getDatePatternForLocale,
getDateTimeForTimezone
} from 'iso-locale-tools'
const distance = convertDistance(2, "kilometer")
const dateFnsLocaleDirect = getDateFnsLocale("en-AU")
const dateFnsLocaleClosest = getDateFnsLocale("es-PY")
const dateFnsLocaleFallback = getDateFnsLocale("aay")
const dateFnsLocaleFallbackCustom = getDateFnsLocale("aay", { fallbackLocale: "en-CA" })
const datePattern = getDatePatternForLocale("nl-AW")
const dateTimeInTimezone = getDateTimeForTimezone({
date: 1636911831222,
dateTimeFormat: "dd-MM-yyyy HH:mm",
timezone: "Africa/Windhoek",
})
Location
bearingToDirection(bearing: number): Directions | undefined
: converts a bearing (in degrees) to a given cardinal directiongetCenterOfCoordinates(coordinates: Coordinates[]): Coordinates
: finds the direct center of a group of coordinatesgetRhumbLine(fromLongitude: number, toLongitude: number): number
: gets a rhumb line between 2 longitudesgeographicDistanceTo({ from, to, unit, useRhumbLine }: { from: Coordinates, to: Coordinates, unit: DistanceUnit, useRhumbLine?: boolean }): number
: get the great-circle distance between 2 points (using haversine formula). set useRhumbLine
to true
to get the distance between 2 points using a rhumb line.bearingDistanceTo({ from, to, useRhumbLine }: { from: Coordinates, to: Coordinates, useRhumbLine?: boolean }): { initialBearing: number, finalBearing: number})
: returns the initial bearing from start point to destination point, and the final bearing which differs by varying degrees according to the lat/long. set useRhumbLine
to true
to get the bearings over a rhumb line.
import {
bearingToDirection,
getCenterOfCoordinates,
getRhumbLine,
geographicDistanceTo,
bearingDistanceTo
} from 'iso-locale-tools'
const direction = bearingToDirection(261)
const location1 = { latitude: 12.5, longitude: -69.9 }
const location2 = { latitude: 52.5, longitude: 5.75 }
const center = getCenterOfCoordinates([
location1,
location2
])
const rhumbLine = getRhumbLine(location1.longitude, location2.longitude)
const distance = geographicDistanceTo({ from: location1, to: location2, unit: "mile" })
const distanceUsingRhumbLine = geographicDistanceTo({ from: location1, to: location2, unit: "kilometer", useRhumbLine: true })
const bearing = bearingDistanceTo({ from: location1, to: location2 })
const bearingUsingRhumbLine = const bearing = bearingDistanceTo({ from: location1, to: location2, useRhumbLine: true })
Acknowledgements