CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-i18n-iso-countries

i18n for ISO 3166-1 country codes with support for 79 languages and bidirectional conversion between Alpha-2, Alpha-3, and Numeric codes

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

locale-management.mddocs/

Locale Management

Register and manage language data for browser environments and query supported languages. Essential for browser-based applications that need selective language loading for optimal performance.

Capabilities

Register Locale Data

Registers language data for use in browser environments. Required before using name-related functions in browser contexts.

/**
 * Register locale data for browser environment
 * @param localeData - Object containing locale identifier and country name mappings
 * @throws TypeError if localeData.locale or localeData.countries is missing
 */
function registerLocale(localeData: LocaleData): void;

interface LocaleData {
  locale: string;
  countries: { [alpha2Key: string]: string | string[] };
}

Usage Examples:

const countries = require("i18n-iso-countries");

// Register English locale
countries.registerLocale(require("i18n-iso-countries/langs/en.json"));

// Register multiple locales
countries.registerLocale(require("i18n-iso-countries/langs/fr.json"));
countries.registerLocale(require("i18n-iso-countries/langs/de.json"));
countries.registerLocale(require("i18n-iso-countries/langs/es.json"));

// Now you can use name functions
console.log(countries.getName("US", "en"));  // "United States of America"
console.log(countries.getName("US", "fr"));  // "États-Unis"
console.log(countries.getName("US", "de"));  // "Vereinigte Staaten von Amerika"

// Custom locale data registration
const customLocale = {
  locale: "test",
  countries: {
    "US": "Test United States",
    "GB": ["Test United Kingdom", "Test UK"],
    "DE": "Test Germany"
  }
};
countries.registerLocale(customLocale);
console.log(countries.getName("US", "test")); // "Test United States"
console.log(countries.getName("GB", "test", { select: "alias" })); // "Test UK"

Error Handling in Registration

const countries = require("i18n-iso-countries");

// Missing locale property
try {
  countries.registerLocale({
    countries: { "US": "United States" }
  });
} catch (error) {
  console.log(error.message); // "Missing localeData.locale"
}

// Missing countries property
try {
  countries.registerLocale({
    locale: "en"
  });
} catch (error) {
  console.log(error.message); // "Missing localeData.countries"
}

// Invalid structure - countries must be an object
try {
  countries.registerLocale({
    locale: "en",
    countries: "invalid"
  });
} catch (error) {
  console.log(error.message); // "Missing localeData.countries"
}

Get Supported Languages

Retrieves the complete list of language codes supported by the library.

/**
 * Get all supported language codes
 * @returns Array of ISO 639-1 language codes supported by the library
 */
function getSupportedLanguages(): string[];

Usage Examples:

const countries = require("i18n-iso-countries");

const supportedLangs = countries.getSupportedLanguages();

console.log(supportedLangs.length); // 79

// Check if a language is supported
function isLanguageSupported(langCode) {
  return supportedLangs.includes(langCode);
}

console.log(isLanguageSupported("en")); // true
console.log(isLanguageSupported("fr")); // true
console.log(isLanguageSupported("xx")); // false

// Display supported languages
console.log("Supported languages:", supportedLangs.join(", "));
// Output: br, cy, dv, sw, eu, af, am, ha, ku, ml, mt, no, ps, sd, so, sq, ta, tg, tt, ug, ur, vi, ar, az, be, bg, bn, bs, ca, cs, da, de, el, en, es, et, fa, fi, fr, ga, gl, he, hi, hr, hu, hy, id, is, it, ja, ka, kk, km, ko, ky, lt, lv, mk, mn, mr, ms, nb, nl, nn, pl, pt, ro, ru, sk, sl, sr, sv, th, tk, tr, uk, uz, zh

// Iterate through supported languages
supportedLangs.forEach(lang => {
  console.log(`Language: ${lang}`);
});

Get Registered Languages

Retrieves the list of currently registered/loaded language codes in the current environment.

/**
 * Get currently registered language codes
 * @returns Array of language codes that have been registered in the current session
 */
function langs(): string[];

Usage Examples:

const countries = require("i18n-iso-countries");

// Initially, in browser environment, no languages are registered
console.log(countries.langs()); // []

// Register some languages
countries.registerLocale(require("i18n-iso-countries/langs/en.json"));
countries.registerLocale(require("i18n-iso-countries/langs/fr.json"));

// Now these languages are available
console.log(countries.langs()); // ["en", "fr"]

// Register more languages
countries.registerLocale(require("i18n-iso-countries/langs/de.json"));
countries.registerLocale(require("i18n-iso-countries/langs/es.json"));

console.log(countries.langs()); // ["en", "fr", "de", "es"]

// Check if specific language is registered
function isLanguageRegistered(langCode) {
  return countries.langs().includes(langCode);
}

console.log(isLanguageRegistered("en")); // true
console.log(isLanguageRegistered("zh")); // false (not registered yet)

Environment Differences

Node.js Environment

In Node.js, all supported languages are automatically pre-loaded:

const countries = require("i18n-iso-countries");

// All 79 languages are immediately available
console.log(countries.langs().length); // 79
console.log(countries.getSupportedLanguages().length); // 79

// langs() and getSupportedLanguages() return the same list
console.log(countries.langs().sort()); 
console.log(countries.getSupportedLanguages().sort());
// Both return the same 79 language codes

// No registration needed
console.log(countries.getName("US", "zh")); // Works immediately
console.log(countries.getName("US", "ar")); // Works immediately

Browser Environment

In browser environments, languages must be manually registered:

const countries = require("i18n-iso-countries");

// Initially no languages registered
console.log(countries.langs()); // []
console.log(countries.getSupportedLanguages().length); // 79 (full list available)

// Functions return undefined for unregistered languages
console.log(countries.getName("US", "en")); // undefined

// Register required languages
countries.registerLocale(require("i18n-iso-countries/langs/en.json"));
countries.registerLocale(require("i18n-iso-countries/langs/fr.json"));

// Now registered languages work
console.log(countries.langs()); // ["en", "fr"]
console.log(countries.getName("US", "en")); // "United States of America"
console.log(countries.getName("US", "fr")); // "États-Unis"
console.log(countries.getName("US", "de")); // undefined (not registered)

Locale Data Structure

Understanding the structure of locale data files helps with custom registrations:

// Example structure of a locale file (en.json)
const enLocale = {
  "locale": "en",
  "countries": {
    "AF": "Afghanistan",
    "AL": "Albania",
    "DZ": "Algeria",
    // ... more countries with single names
    "GB": ["United Kingdom", "UK", "Great Britain"], // Country with aliases
    // ... more countries
  }
};

// Countries can have either:
// 1. Single name (string): "Germany"
// 2. Multiple names (array): ["United Kingdom", "UK", "Great Britain"]
//    - First element is the official name
//    - Additional elements are aliases

Performance and Bundle Size Optimization

Selective Loading Strategy

// Bundle size optimization - only load needed languages
const countries = require("i18n-iso-countries");

// Application supports English, French, and Spanish
const supportedAppLanguages = ["en", "fr", "es"];

// Load only required languages
supportedAppLanguages.forEach(lang => {
  countries.registerLocale(require(`i18n-iso-countries/langs/${lang}.json`));
});

// Verify registration
console.log("Loaded languages:", countries.langs());

// Create language validation function
function validateLanguage(langCode) {
  return countries.langs().includes(langCode);
}

Dynamic Language Loading

async function loadLanguage(langCode) {
  // Check if already registered
  if (countries.langs().includes(langCode)) {
    return true;
  }
  
  // Check if language is supported
  if (!countries.getSupportedLanguages().includes(langCode)) {
    throw new Error(`Language '${langCode}' is not supported`);
  }
  
  try {
    // Dynamically import and register
    const localeData = require(`i18n-iso-countries/langs/${langCode}.json`);
    countries.registerLocale(localeData);
    return true;
  } catch (error) {
    throw new Error(`Failed to load language '${langCode}': ${error.message}`);
  }
}

// Usage
async function getCountryNameWithLazyLoading(countryCode, langCode) {
  await loadLanguage(langCode);
  return countries.getName(countryCode, langCode);
}

// Example
getCountryNameWithLazyLoading("US", "de").then(name => {
  console.log(name); // "Vereinigte Staaten von Amerika"
});

Language Code Reference

The library uses ISO 639-1 language codes. Here's the complete list of supported languages:

  • af: Afrikaans
  • am: Amharic
  • ar: Arabic
  • az: Azerbaijani
  • be: Belorussian
  • bg: Bulgarian
  • bn: Bengali
  • br: Breton
  • bs: Bosnian
  • ca: Catalan
  • cs: Czech
  • cy: Cymraeg (Welsh)
  • da: Danish
  • de: German
  • dv: Dhivehi
  • el: Greek
  • en: English
  • es: Spanish
  • et: Estonian
  • eu: Basque
  • fa: Persian
  • fi: Finnish
  • fr: French
  • ga: Irish
  • gl: Galician
  • ha: Hausa
  • he: Hebrew
  • hi: Hindi
  • hr: Croatian
  • hu: Hungarian
  • hy: Armenian
  • id: Indonesian
  • is: Icelandic
  • it: Italian
  • ja: Japanese
  • ka: Georgian
  • kk: Kazakh
  • km: Khmer
  • ko: Korean
  • ku: Kurdish
  • ky: Kyrgyz
  • lt: Lithuanian
  • lv: Latvian
  • mk: Macedonian
  • ml: Malayalam
  • mn: Mongolian
  • mr: Marathi
  • ms: Malay
  • mt: Maltese
  • nb: Norwegian Bokmål
  • nl: Dutch
  • nn: Norwegian Nynorsk
  • no: Norwegian
  • pl: Polish
  • ps: Pashto
  • pt: Portuguese
  • ro: Romanian
  • ru: Russian
  • sd: Sindhi
  • sk: Slovak
  • sl: Slovene
  • so: Somali
  • sq: Albanian
  • sr: Serbian
  • sv: Swedish
  • sw: Swahili
  • ta: Tamil
  • tg: Tajik
  • th: Thai
  • tk: Turkmen
  • tr: Turkish
  • tt: Tatar
  • ug: Uyghur
  • uk: Ukrainian
  • ur: Urdu
  • uz: Uzbek
  • vi: Vietnamese
  • zh: Chinese

Error Prevention

Safe Registration Pattern

function safeRegisterLocale(langCode) {
  try {
    // Check if already registered
    if (countries.langs().includes(langCode)) {
      return { success: true, message: `Language '${langCode}' already registered` };
    }
    
    // Check if supported
    if (!countries.getSupportedLanguages().includes(langCode)) {
      return { success: false, message: `Language '${langCode}' is not supported` };
    }
    
    // Load and register
    const localeData = require(`i18n-iso-countries/langs/${langCode}.json`);
    countries.registerLocale(localeData);
    
    return { success: true, message: `Language '${langCode}' registered successfully` };
  } catch (error) {
    return { success: false, message: `Failed to register '${langCode}': ${error.message}` };
  }
}

// Usage
console.log(safeRegisterLocale("en")); // { success: true, message: "Language 'en' registered successfully" }
console.log(safeRegisterLocale("xx")); // { success: false, message: "Language 'xx' is not supported" }

docs

code-conversion.md

index.md

listings-validation.md

locale-management.md

name-retrieval.md

name-to-code.md

tile.json