npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

countries-states-cities-neighborhood-database

v1.2.3

Published

contains country, state, cities, neighborhood, and building data

Readme

Countries-States-Cities-Neighborhood Database

A comprehensive library for working with country, state/region, city, and neighborhood data. This npm package provides simple, intuitive functions to query and filter location data from around the world.

Table of Contents

Installation

npm install countries-states-cities-neighborhood-database

Usage

The package provides two ways to use the library:

1. API Factory (Recommended)

The API factory pattern is the simplest way to use the library, as it loads the dataset automatically:

const locationDB = require('countries-states-cities-neighborhood-database');
const api = locationDB.createAPI();

// Get all countries
const countries = api.getAllCountries();

// Get all cities in the United States
const usCities = api.getCitiesByCountry('US');

// Find cities near a location (within 50km)
const nearbyCities = api.getCitiesByGeoLocation(40.7128, -74.0060, 50);

2. Direct Function Access

You can also use the functions directly with your own dataset:

const locationDB = require('countries-states-cities-neighborhood-database');
const data = require('./path/to/your/data.json');

// Get all countries
const countries = locationDB.getAllCountries(data);

// Get all cities in the United States
const usCities = locationDB.getCitiesByCountry(data, 'US');

// Find cities near a location (within 50km)
const nearbyCities = locationDB.getCitiesByGeoLocation(data, 40.7128, -74.0060, 50);

Data Structure

This library expects your data to follow a specific structure:

[
  {
    "id": 231,
    "name": "United States",
    "iso2": "US",
    "iso3": "USA",
    "states": [
      {
        "id": 3901,
        "name": "California",
        "state_code": "CA",
        "cities": [
          {
            "id": 52327,
            "name": "San Francisco",
            "latitude": "37.77493",
            "longitude": "-122.41942"
          }
        ]
      }
    ]
  }
]

API Reference

The examples below show both usage patterns: the API factory method and direct function calls.

Countries

getAllCountries(data)

Returns an array of all countries in the dataset.

  • Parameters:
    • data (Array): The complete dataset (not needed when using API factory)
  • Returns: Array of country objects
  • Example:
    // Using API factory
    const countries = api.getAllCountries();
      
    // Direct function call
    const countries = locationDB.getAllCountries(data);
      
    console.log(countries.length); // Number of countries

getCountryByCode(data, isoCode)

Finds a country by its ISO code (ISO2 or ISO3).

  • Parameters:
    • data (Array): The complete dataset (not needed when using API factory)
    • isoCode (String): ISO2 or ISO3 code to search for
  • Returns: Country object or null if not found
  • Example:
    // Using API factory
    const usa = api.getCountryByCode('US');
    const canada = api.getCountryByCode('CAN');
      
    // Direct function call
    const usa = locationDB.getCountryByCode(data, 'US');
    const canada = locationDB.getCountryByCode(data, 'CAN');

getCountryByName(data, name)

Finds a country by its name.

  • Parameters:
    • data (Array): The complete dataset
    • name (String): Country name to search for
  • Returns: Country object or null if not found
  • Example:
    const japan = getCountryByName(data, 'Japan');

States/Regions

getAllStates(data)

Returns an array of all states/regions from all countries.

  • Parameters:
    • data (Array): The complete dataset
  • Returns: Array of state objects with country info attached
  • Example:
    const allStates = getAllStates(data);
    console.log(allStates[0]); // First state with country information

getStatesByCountry(data, countryIdentifier)

Returns all states for a specific country.

  • Parameters:
    • data (Array): The complete dataset
    • countryIdentifier (String|Number): Country ID, name, or ISO code
  • Returns: Array of state objects or empty array if country not found
  • Example:
    const usStates = getStatesByCountry(data, 'US');
    const canadianProvinces = getStatesByCountry(data, 'Canada');

getStateByCode(data, countryIdentifier, stateCode)

Finds a specific state by its code.

  • Parameters:
    • data (Array): The complete dataset
    • countryIdentifier (String|Number): Country ID, name, or ISO code
    • stateCode (String): State code to search for
  • Returns: State object or null if not found
  • Example:
    const california = getStateByCode(data, 'US', 'CA');

Cities

getAllCities(data)

Returns an array of all cities from all countries.

  • Parameters:
    • data (Array): The complete dataset
  • Returns: Array of city objects with country and state info attached
  • Example:
    const allCities = getAllCities(data);
    console.log(allCities.length); // Total number of cities

getCitiesByCountry(data, countryIdentifier)

Returns all cities for a specific country.

  • Parameters:
    • data (Array): The complete dataset
    • countryIdentifier (String|Number): Country ID, name, or ISO code
  • Returns: Array of city objects with state info attached
  • Example:
    const usCities = getCitiesByCountry(data, 'US');

getCitiesByState(data, countryIdentifier, stateIdentifier)

Returns all cities for a specific state/region.

  • Parameters:
    • data (Array): The complete dataset
    • countryIdentifier (String|Number): Country ID, name, or ISO code
    • stateIdentifier (String|Number): State ID, name, or code
  • Returns: Array of city objects
  • Example:
    const texasCities = getCitiesByState(data, 'US', 'TX');

getCityByName(data, countryIdentifier, stateIdentifier, cityName)

Finds a specific city by name within a state.

  • Parameters:
    • data (Array): The complete dataset
    • countryIdentifier (String|Number): Country ID, name, or ISO code
    • stateIdentifier (String|Number): State ID, name, or code
    • cityName (String): City name to search for
  • Returns: City object or null if not found
  • Example:
    const boston = getCityByName(data, 'US', 'MA', 'Boston');

Neighborhoods

getNeighborhoodsByCity(data, countryIdentifier, stateIdentifier, cityIdentifier, basePath)

Returns all neighborhoods for a specific city.

  • Parameters:
    • data (Array): The complete dataset
    • countryIdentifier (String|Number): Country ID, name, or ISO code
    • stateIdentifier (String|Number): State ID, name, or code
    • cityIdentifier (String|Number): City ID or name
    • basePath (String): Base path for neighborhood data files (default: '../data/json/neighborhoods')
  • Returns: Array of neighborhood objects or empty array if city not found or has no neighborhoods
  • Example:
    const neighborhoods = getNeighborhoodsByCity(data, 'US', 'NY', 'New York');

Search & Geolocation

searchCities(data, query, countryIdentifier)

Searches for cities matching a query across all countries or a specific country.

  • Parameters:
    • data (Array): The complete dataset
    • query (String): Search query
    • countryIdentifier (String|Number, optional): Country to limit search
  • Returns: Array of matching city objects
  • Example:
    const springfields = searchCities(data, 'Springfield');
    const canadianVancouvers = searchCities(data, 'Vancouver', 'CA');

getCitiesByGeoLocation(data, latitude, longitude, radiusKm)

Finds cities within a certain radius of GPS coordinates.

  • Parameters:
    • data (Array): The complete dataset
    • latitude (Number): Latitude coordinate
    • longitude (Number): Longitude coordinate
    • radiusKm (Number): Search radius in kilometers
  • Returns: Array of city objects within the radius, sorted by distance
  • Example:
    // Cities within 50km of NYC
    const citiesNearNYC = getCitiesByGeoLocation(data, 40.7128, -74.0060, 50);

Internal Helper Functions

The library uses these internal helper functions:

  • calculateDistance(lat1, lon1, lat2, lon2): Calculates distance between two points using the Haversine formula
  • toRad(value): Converts degrees to radians

Project Structure

countries-states-cities-neighborhood-database/
│
├── data/
│   └── json/
│       ├── countries+states+cities.json    # Main dataset
│       └── neighborhoods/                  # Neighborhood data
│           └── [STATE_CODE]/
│               └── neighborhoods.json
│
├── src/
│   └── functions.js                        # Core functionality
│
├── index.js                                # API factory & exports
├── package.json
└── README.md

Testing

This package uses Jest for testing:

npm test

TypeScript Usage

The package can be used in TypeScript applications. Here's a basic example with type definitions:

// Type definitions for the database
interface Country {
  id: number;
  name: string;
  iso2: string;
  iso3: string;
  states: State[];
}

interface State {
  id: number;
  name: string;
  state_code: string;
  cities: City[];
}

interface City {
  id: number;
  name: string;
  latitude: string;
  longitude: string;
}

// Using the package with TypeScript
import { createAPI } from 'countries-states-cities-neighborhood-database';

const api = createAPI();
const countries: Country[] = api.getAllCountries();
const usStates: State[] = api.getStatesByCountry('US');

See the full React component example in the examples directory.

License

ISC