google-libphonenumber

repository·master·Indexed 23 days ago

https://github.com/ruimarinho/google-libphonenumber

A Node.js port and 1:1 mirror of Google's libphonenumber library (version 3.2.46) for parsing, formatting, and validating international phone numbers. It provides core utilities such as PhoneNumberUtil, AsYouTypeFormatter, and ShortNumberInfo with zero dependencies.

Tokens
2.5K
Snippets
7
Records
16
Agent score
31%

What's inside google-libphonenumber

  1. Parse raw strings into PhoneNumber objects

    master
    ⚠️ Critical Requirement: Most PhoneNumberUtil methods do not accept raw strings. You must first convert a string into an i18n.phonenumbers.PhoneNumber instance using phoneUtil.parse() or phoneUtil.parseAndKeepRawInput(). Passing a raw string directly will result in a TypeError.
  2. Understand the relationship between google-libphonenumber and the original library

    master

    google-libphonenumber is a 1:1 mirror of the original Google libphonenumber library, pre-compiled as a bundle for Node.js.

    Key characteristics:

    • No API simplifications: All classes from the original libphonenumber are exported as-is. There are no 'magic' methods or simplified wrappers.
    • Up-to-date: It is based on the latest google-closure library version available from Google.
    • Comparison with alternatives:
      • If you want a more user-friendly API, consider awesome-phonenumber.
      • If you want a radical rewrite that doesn't depend on Google Closure (and offers metadata reduction for frontend use), consider libphonenumber-js.
  3. Use the AsYouTypeFormatter for real-time input

    master

    The AsYouTypeFormatter is used to show formatting progress as a user types. You must register every keystroke (digit or symbol) using inputDigit() on a new instance initialized with a default region.

    // Require `AsYouTypeFormatter`.
    const AsYouTypeFormatter = require('google-libphonenumber').AsYouTypeFormatter;
    const formatter = new AsYouTypeFormatter('US');
    
    console.log(formatter.inputDigit('2')); // => 2
    console.log(formatter.inputDigit('0')); // => 20
    console.log(formatter.inputDigit('2')); // => 202
    console.log(formatter.inputDigit('-')); // => 202-
    console.log(formatter.inputDigit('4')); // => 202-4
    console.log(formatter.inputDigit('5')); // => 202-45
    console.log(formatter.inputDigit('6')); // => 202-456
    console.log(formatter.inputDigit('-')); // => 202-456-
    console.log(formatter.inputDigit('1')); // => 202-456-1
    console.log(formatter.inputDigit('4')); // => 202-456-14
    console.log(formatter.inputDigit('1')); // => 202-456-141
    console.log(formatter.inputDigit('4')); // => 202-456-1414
    
    // Cleanup all input digits from instance.
    formatter.clear();
  4. Fix UTF-8 encoding errors in Chrome Extensions using Webpack

    master

    When compiling Chrome Extensions with Webpack, you may encounter the error: Could not load file 'file.js' for content script. It isn't UTF-8 encoded. This happens because the Google Closure Compiler API may not always return fully compliant UTF-8-encoded output.

    To resolve this, configure TerserPlugin to output US-ASCII characters only.

    optimization: {
      minimize: process.env.NODE_ENV !== 'development',
      minimizer: [
        new TerserPlugin({
          terserOptions: {
            output: {
              ascii_only: true
            }
          },
        }),
      ]
    }
  5. Troubleshoot metadata and carrier issues

    master

    If you encounter unexpected phone validations, formatting errors, or unknown carriers, the issue is likely related to carrier metadata.

    To determine the cause:

    1. Test the same input using the official Google libphonenumber demo page.
    2. If the results differ, the google-libphonenumber package may need a metadata update.
    3. If the results are the same, the issue exists in the original metadata and should be reported to the original project's issue tracker.
  6. Basic phone number extraction and validation

    master

    Use PhoneNumberUtil.getInstance() to access core utilities. You can parse numbers, validate them, and extract metadata like country codes and national numbers.

    // Require `PhoneNumberFormat`.
    const PNF = require('google-libphonenumber').PhoneNumberFormat;
    
    // Get an instance of `PhoneNumberUtil`.
    const phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();
    
    // Parse number with country code and keep raw input.
    const number = phoneUtil.parseAndKeepRawInput('202-456-1414', 'US');
    
    // Print the phone's country code.
    console.log(number.getCountryCode());
    // => 1
    
    // Print the phone's national number.
    console.log(number.getNationalNumber());
    // => 2024561414
    
    // Print the phone's extension.
    console.log(number.getExtension());
    // =>
    
    // Print the phone's country code source.
    console.log(number.getCountryCodeSource());
    // => FROM_DEFAULT_COUNTRY
    
    // Print the phone's raw input.
    console.log(number.getRawInput());
    // => 202-456-1414
    
    // Validation results
    console.log(phoneUtil.isPossibleNumber(number));
    // => true
    
    console.log(phoneUtil.isValidNumber(number));
    // => true
    
    console.log(phoneUtil.isValidNumberForRegion(number, 'US'));
    // => true
    
    // Metadata results
    console.log(phoneUtil.getRegionCodeForNumber(number));
    // => US
    
    console.log(phoneUtil.getNumberType(number));
    // => FIXED_LINE_OR_MOBILE
  7. Format phone numbers in different styles

    master

    Once you have a PhoneNumber instance, use phoneUtil.format() with a PhoneNumberFormat enum to change the display style.

    const PNF = require('google-libphonenumber').PhoneNumberFormat;
    const phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();
    const number = phoneUtil.parseAndKeepRawInput('202-456-1414', 'US');
    
    // E164 format
    console.log(phoneUtil.format(number, PNF.E164));
    // => +12024561414
    
    // Original format
    console.log(phoneUtil.formatInOriginalFormat(number, 'US'));
    // => (202) 456-1414
    
    // National format
    console.log(phoneUtil.format(number, PNF.NATIONAL));
    // => (202) 456-1414
    
    // International format
    console.log(phoneUtil.format(number, PNF.INTERNATIONAL));
    // => +1 202-456-1414
    
    // Out-of-country format from US
    console.log(phoneUtil.formatOutOfCountryCallingNumber(number, 'US'));
    // => 1 (202) 456-1414
    
    // Out-of-country format from CH
    console.log(phoneUtil.formatOutOfCountryCallingNumber(number, 'CH'));
    // => 00 1 202-456-1414