### Configuration and Examples - Reference Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/README.md Covers installation, project setup, database file configuration, synchronous and asynchronous usage patterns, Express.js integration, and performance optimization. ```APIDOC ## Configuration and Examples ### Description This section guides users through the setup, configuration, and common usage patterns of the IP2Location Node.js library. ### Setup and Configuration - Installation instructions and project setup. - Configuring database files, including download information. - Web service and CSV data file setup. - Environment variable usage. ### Usage Patterns - Synchronous vs. asynchronous operation modes. - Examples of Express.js integration. - Performance optimization tips. - Testing setup guidance. ``` -------------------------------- ### Setup Local Database Files Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/INDEX.md Details the process of downloading and setting up local database files for use with the library. ```text Database Files ├── Download from: https://www.ip2location.com/download ├── Packages: LITE, DB1, DB3, DB4, DB9, DB25 └── Setup: Place file, call open(path) → See: configuration-and-examples.md ``` -------------------------------- ### Install ip2location-nodejs Source: https://github.com/ip2location/ip2location-nodejs/blob/master/docs/source/quickstart.md Install the IP2Location Node.js module using npm. ```bash npm install ip2location-nodejs ``` -------------------------------- ### Handle Configuration Errors Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/ip2locationwebservice-class.md This example shows how to catch configuration errors, such as an invalid API key, which are thrown immediately by the `open()` method. ```javascript try { ws.open('INVALID', 'BAD'); // Throws immediately } catch (err) { console.error('Configuration error:', err.message); } ``` -------------------------------- ### Setup Country CSV Files Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/INDEX.md Provides instructions for downloading and setting up country information CSV files. ```text CSV Files ├── Country: https://www.ip2location.com/database/country-information ├── Region: https://www.ip2location.com/database/region-information └── Setup: new Country(path), new Region(path) → See: country-region-classes.md ``` -------------------------------- ### TypeScript Initialization Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/configuration-and-examples.md Initialize the IP2Location database using TypeScript. This example demonstrates the import and instantiation process for TypeScript projects. ```typescript import { IP2Location, IP2LocationWebService, IPTools, Country, Region } from 'ip2location-nodejs'; const db: IP2Location = new IP2Location(); db.open('./IP2LOCATION-LITE-DB1.BIN'); ``` -------------------------------- ### Get Country Information Example Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/types.md Demonstrates how to retrieve country information using the `getCountryInfo` method and access the country code. Ensure the 'US' country data is available. ```javascript const info = await country.getCountryInfo('US'); console.log(info[0].country_code); // "US" ``` -------------------------------- ### Lookup Request URL Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/ip2locationwebservice-class.md Example of a GET request URL for the lookup function, including parameters for API key, package, IP address, add-ons, and language. ```http GET https://api.ip2location.com/v2/?key=ABCDEF1234&package=WS1&ip=8.8.8.8&addon=continent,country&lang=en ``` -------------------------------- ### Get Credit Request URL Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/ip2locationwebservice-class.md Example of a GET request URL for checking remaining credits. It requires the API key and a 'check' parameter set to true. ```http GET https://api.ip2location.com/v2/?key=ABCDEF1234&check=true ``` -------------------------------- ### Get Package Version Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/ip2location-class.md Retrieves the database package version number. ```javascript getPackageVersion(): number ``` -------------------------------- ### Express.js Usage Example with IP2Location Middleware Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/types.md Demonstrates how to integrate the IP2Location middleware into an Express.js application to retrieve geolocation data. ```javascript const express = require('express'); const { IP2Location } = require('ip2location-nodejs'); const app = express(); const db = new IP2Location(); db.open('./IP2LOCATION-LITE-DB1.BIN'); app.use(db.middleware()); app.get('/location', (req, res) => { if (req.ip2location.status === 'OK') { res.json({ country: req.ip2location.countryLong, city: req.ip2location.city }); } else { res.status(400).json({ error: req.ip2location.status }); } }); ``` -------------------------------- ### IP2Location Mock Data for Unit Tests Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/configuration-and-examples.md Set up mock data and test fixtures for unit testing the geolocation service. This example demonstrates initializing the IP2Location database with a test BIN file and asserting results for valid and invalid IP addresses. ```javascript // test/geoip.test.js const { IP2Location } = require('ip2location-nodejs'); describe('Geolocation Service', () => { let db; beforeAll(() => { db = new IP2Location(); db.open('./test/fixtures/IP2LOCATION-LITE-DB1.BIN'); }); afterAll(() => { db.close(); }); test('should return country for valid IP', () => { const result = db.getCountryShort('8.8.8.8'); expect(result).toMatch(/^[A-Z]{2}$/); }); test('should handle invalid IPs', () => { const result = db.getAll('invalid'); expect(result.countryShort).toBe('INVALID_IP_ADDRESS'); }); }); ``` -------------------------------- ### Get API Version Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/ip2location-class.md Retrieves the API version string. ```javascript getAPIVersion(): string ``` -------------------------------- ### Using MODES for Specific Geolocation Queries Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/types.md Examples demonstrating how to use MODES constants to fetch specific geolocation data like country or city. ```javascript // Get only country information db.geoQuery('8.8.8.8', MODES.COUNTRY_SHORT); // Get only city information db.geoQuery('8.8.8.8', MODES.CITY); // Get all available fields db.geoQuery('8.8.8.8', MODES.ALL); ``` -------------------------------- ### Quick Reference - Reference Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/README.md A fast lookup guide for common tasks, method signatures, mode constants, error references, database package field availability, code patterns, and return type references. ```APIDOC ## Quick Reference ### Description This section serves as a quick lookup guide for essential information about the IP2Location Node.js library. ### Contents - Common tasks and their corresponding methods. - Method signatures presented at a glance. - Overview of mode constants. - Table summarizing error references. - Information on field availability based on the database package. - Examples of common code patterns. - Reference for return types. ``` -------------------------------- ### Initialize and Get All Country Information from CSV Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/configuration-and-examples.md Initialize the Country module with a local CSV file path and retrieve all country information. Ensure the CSV file is downloaded from the provided link. ```javascript const { Country } = require('ip2location-nodejs'); // Initialize with country CSV const country = new Country('./IP2LOCATION-COUNTRY-INFORMATION.CSV'); // Get all countries (async () => { const allCountries = await country.getCountryInfo(); console.log(`Loaded ${allCountries.length} countries`); // Get specific country const us = await country.getCountryInfo('US'); console.log('US:', us[0]); })(); ``` -------------------------------- ### Get Database Version Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/ip2location-class.md Retrieves the database version in YYYY.MM.DD format. ```javascript getDatabaseVersion(): string ``` -------------------------------- ### Configure IP2Location Web Service API Key Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/INDEX.md Explains the format and setup for API keys used with the IP2Location Web Service. ```text API Keys ├── Format: 10 uppercase alphanumeric characters ├── Package: WS (e.g., WS1, WS25) └── Setup: ws.open(key, package) → See: ip2locationwebservice-class.md ``` -------------------------------- ### Initialize Region Class Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/country-region-classes.md Instantiate the Region class with the path to the region information CSV file. Note that CSV parsing is asynchronous and starts immediately upon instantiation. ```javascript const { Region } = require('ip2location-nodejs'); try { const region = new Region('./regions.csv'); // Note: parsing happens asynchronously, use await getRegionCode() } catch (err) { console.error('Failed to initialize Region:', err.message); } ``` -------------------------------- ### Region Constructor Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/country-region-classes.md Initializes the Region class with a path to a region information CSV file. Asynchronous CSV parsing starts immediately upon instantiation. Errors are thrown for file not found, invalid CSV structure, or read errors. ```APIDOC ## Constructor Region ### Description Initializes the Region class with a path to a region information CSV file. Asynchronous CSV parsing starts immediately upon instantiation. Errors are thrown for file not found, invalid CSV structure, or read errors. ### Parameters #### Path Parameters - **csvFile** (string) - Required - Full or relative path to region information CSV file ### Throws - `Error: "The CSV file is not found."` - File does not exist - `Error: "Invalid region information CSV file."` - CSV structure invalid - `Error: "Unable to read ."` - File read error ### Example ```javascript const { Region } = require('ip2location-nodejs'); try { const region = new Region('./regions.csv'); // Note: parsing happens asynchronously, use await getRegionCode() } catch (err) { console.error('Failed to initialize Region:', err.message); } ``` ### CSV Format Expected - Header row with columns: `country_code`, `code`, `subdivision_name` - One record per region/subdivision - UTF-8 encoding ``` -------------------------------- ### Example Error Response Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/types.md Illustrates the structure of an error response when an IP address is invalid or data is unavailable. All non-text fields are set to 'INVALID_IP_ADDRESS' for invalid IP errors. ```javascript { ip: "invalid", ipNo: "INVALID_IP_ADDRESS", countryShort: "INVALID_IP_ADDRESS", countryLong: "INVALID_IP_ADDRESS", // ... all other fields also "INVALID_IP_ADDRESS" } ``` -------------------------------- ### Initialize and Get Region Information from CSV Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/configuration-and-examples.md Initialize the Region module with a local CSV file path and retrieve region codes by country and region name. The region name lookup is case-insensitive. ```javascript const { Region } = require('ip2location-nodejs'); // Initialize with region CSV const region = new Region('./IP2LOCATION-REGION-INFORMATION.CSV'); // Get region code (async () => { const code = await region.getRegionCode('US', 'California'); console.log('Region code:', code); // "CA" // Get region by name (case-insensitive) const code2 = await region.getRegionCode('US', 'texas'); console.log('Region code:', code2); // "TX" })(); ``` -------------------------------- ### IP2Location Node.js Error Handling Example Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/ip2location-class.md Demonstrates how invalid IP addresses are handled, returning geolocation objects with error messages. Use this to understand how to check for and interpret errors in query results. ```javascript const result = db.getAll('invalid-ip'); console.log(result.city); // "INVALID_IP_ADDRESS" ``` -------------------------------- ### open(apiKey, apiPackage, useSSL) Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/ip2locationwebservice-class.md Initializes the web service with API credentials and configuration. This method must be called before making any lookup or credit check requests. ```APIDOC ## Configuration: open(apiKey, apiPackage, useSSL) Initializes the web service with API credentials and configuration. ```javascript open(apiKey: string, apiPackage: string, useSSL?: boolean): void ``` ### Parameters #### Path Parameters - **apiKey** (string) - Required - IP2Location API key (format: 10 alphanumeric characters) - **apiPackage** (string) - Required - Package name to query (format: `WS`, e.g., `WS1`, `WS25`) - **useSSL** (boolean) - Optional - Use HTTPS (true) or HTTP (false) for API requests (Default: `true`) ### Throws - `Error: "Invalid API key."` if apiKey format is invalid - `Error: "Invalid package name."` if apiPackage format is invalid ### Example ```javascript const { IP2LocationWebService } = require('ip2location-nodejs'); const ws = new IP2LocationWebService(); ws.open('ABCDEF1234', 'WS1', true); ``` ``` -------------------------------- ### Constructor Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/iptools-class.md Creates a new IPTools utility instance. No parameters are required. ```APIDOC ## Constructor ### Description Creates a new IPTools utility instance. No parameters are required. ### Method ```javascript new IPTools() ``` ``` -------------------------------- ### Open IP2Location Database (Synchronous) Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/ip2location-class.md Initializes the module with the path to an IP2Location BIN file and pre-loads metadata synchronously. Throws an error if the BIN file format is invalid or corrupted. ```javascript const IP2Location = require('ip2location-nodejs').IP2Location; const db = new IP2Location(); db.open('./IP2LOCATION-LITE-DB1.BIN'); ``` -------------------------------- ### Initialize and Lookup with API Key Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/configuration-and-examples.md Initialize the Web Service client with your API key and perform a lookup for IP address data. Ensure you replace 'YOUR_API_KEY' with your actual key. ```javascript const { IP2LocationWebService } = require('ip2location-nodejs'); const ws = new IP2LocationWebService(); // Initialize with API key ws.open('YOUR_API_KEY', 'WS1', true); // useSSL=true // Perform lookup ws.lookup('8.8.8.8', 'continent,country,state,city', 'en', (error, result) => { if (error) { console.error('Error:', error); } else { console.log('Result:', result); } }); ``` -------------------------------- ### openAsync(binPath) Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/ip2location-class.md Initializes the module with the path to an IP2Location BIN file and pre-loads metadata asynchronously. It returns a Promise that resolves when the metadata is loaded. The binPath parameter is a string representing the path to the BIN file. ```APIDOC ## openAsync(binPath) ### Description Initializes the module with the path to an IP2Location BIN file and pre-loads metadata asynchronously. ### Method openAsync ### Parameters #### Path Parameters - **binPath** (string) - Required - Full or relative path to the .BIN database file ### Example ```javascript const db = new IP2Location(); await db.openAsync('./IP2LOCATION-LITE-DB1.BIN'); ``` ``` -------------------------------- ### Convert IPv4 CIDR to Address Range Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/iptools-class.md Converts an IPv4 CIDR notation string into its corresponding start and end IP address range. Validates that the CIDR contains a single '/', a valid IPv4 address, and a prefix between 0 and 32. Returns an array with the start and end IP addresses or null if the format is invalid. ```javascript const [start, end] = tools.cidrToIPV4('192.168.0.0/24'); console.log(start); // "192.168.0.0" console.log(end); // "192.168.0.255" const [start2, end2] = tools.cidrToIPV4('10.0.0.0/30'); console.log(start2); // "10.0.0.0" console.log(end2); // "10.0.0.3" ``` -------------------------------- ### Instantiate IPTools Class Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/iptools-class.md Creates a new instance of the IPTools utility class. No parameters are required. ```javascript new IPTools() ``` -------------------------------- ### Convert IPv6 CIDR to Address Range Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/iptools-class.md Converts an IPv6 CIDR notation string to its start and end IP address range in expanded notation. Validates the CIDR format, ensuring it contains a single '/', a valid IPv6 address, and a prefix between 0 and 128. Returns an array containing the start and end IP addresses or null if the format is invalid. ```javascript const [start, end] = tools.cidrToIPV6('2001:db8::/32'); console.log(start); // "2001:db8:0:0:0:0:0:0" console.log(end); // "2001:db8:ffff:ffff:ffff:ffff:ffff:ffff" ``` -------------------------------- ### Synchronous Get All Geolocation Fields Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/ip2location-class.md Use getAll to synchronously retrieve all available geolocation fields for a given IP address. ```javascript const result = db.getAll('1.1.1.1'); console.log(result); ``` -------------------------------- ### Query Local IP2Location BIN Database Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/quick-reference.md Demonstrates how to open a local BIN database, perform single-field and all-field lookups for an IP address, and use asynchronous methods for database operations. ```javascript const db = new IP2Location(); db.open('./IP2LOCATION-LITE-DB1.BIN'); // Single field console.log(db.getCountryShort('8.8.8.8')); // All fields console.log(db.getAll('8.8.8.8')); // Async await db.openAsync('./IP2LOCATION-LITE-DB1.BIN'); const result = await db.getAllAsync('8.8.8.8'); await db.closeAsync(); ``` -------------------------------- ### Base Conversion Example Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/iptools-class.md Converts a number represented as a string from one base to another. Useful for internal CIDR calculations. ```javascript const hex = tools.baseConvert('1111', 2, 16); console.log(hex); // "f" const dec = tools.baseConvert('ff', 16, 10); console.log(dec); // "255" ``` -------------------------------- ### Basic JavaScript Initialization Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/configuration-and-examples.md Initialize the IP2Location database, web service, and IPTools utility in a Node.js environment. Ensure you have the database file and a valid API key. ```javascript const { IP2Location, IP2LocationWebService, IPTools, Country, Region } = require('ip2location-nodejs'); // Initialize database const db = new IP2Location(); db.open('./IP2LOCATION-LITE-DB1.BIN'); // Initialize web service const ws = new IP2LocationWebService(); ws.open('YOUR_API_KEY', 'WS1'); // Initialize utilities const tools = new IPTools(); ``` -------------------------------- ### Error Handling: File Not Found Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/country-region-classes.md Demonstrates how to handle 'File not found' errors that are thrown during the construction of Country or Region instances. ```javascript try { const country = new Country('./missing.csv'); } catch (err) { console.error(err.message); // "The CSV file ./missing.csv is not found." } ``` -------------------------------- ### Convert IPv6 Range to CIDR Notation Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/quick-reference.md Converts a given IPv6 address range (start and end IP) into CIDR notation. ```javascript // IPv6 const cidrs6 = tools.ipV6ToCIDR('2001:db8::1', '2001:db8::ffff'); ``` -------------------------------- ### open(binPath) Source: https://github.com/ip2location/ip2location-nodejs/blob/master/docs/source/code.md Loads the IP2Location BIN database synchronously. This method requires the file path to the BIN database. ```APIDOC ### open(binPath) Load the IP2Location BIN database for lookup. * **Parameters:** **binPath** (*str*) – (Required) The file path links to IP2Location BIN databases. This method synchronously loads the specified IP2Location BIN database file, making it available for subsequent IP address lookups. ``` -------------------------------- ### Initialize IP2LocationWebService with Credentials Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/ip2locationwebservice-class.md Initializes the web service client with API key, package name, and SSL configuration. Ensure your API key and package name are valid before calling. ```javascript const { IP2LocationWebService } = require('ip2location-nodejs'); const ws = new IP2LocationWebService(); ws.open('ABCDEF1234', 'WS1', true); ``` -------------------------------- ### Open IP2Location Database (Asynchronous) Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/ip2location-class.md Initializes the module with the path to an IP2Location BIN file and pre-loads metadata asynchronously. Use this for non-blocking operations. ```javascript const db = new IP2Location(); await db.openAsync('./IP2LOCATION-LITE-DB1.BIN'); ``` -------------------------------- ### Instantiate IP2LocationWebService Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/ip2locationwebservice-class.md Creates a new instance of the IP2LocationWebService client. No parameters are required for basic instantiation. ```javascript new IP2LocationWebService() ``` -------------------------------- ### ipV6ToCIDR(ip_from, ip_to) Source: https://github.com/ip2location/ip2location-nodejs/blob/master/docs/source/code.md Converts a range of IPv6 addresses into a list of CIDR notations. Requires the starting and ending IPv6 addresses of the range. ```APIDOC ## ipV6ToCIDR(ip_from, ip_to) ### Description Convert IPv6 range into a list of IPv6 CIDR notation. ### Parameters #### Path Parameters - **ip_from** (str) - Required - The starting IPv6 address in the range. - **ip_to** (str) - Required - The ending IPv6 address in the range. ### Returns - array - The list of IPv6 CIDR notation. ``` -------------------------------- ### Initialize IP2Location Class Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/ip2location-class.md Creates a new IP2Location instance. No parameters are required for initialization. ```javascript new IP2Location() ``` -------------------------------- ### ipV4ToCIDR(ip_from, ip_to) Source: https://github.com/ip2location/ip2location-nodejs/blob/master/docs/source/code.md Converts a range of IPv4 addresses into a list of CIDR notations. Requires the starting and ending IPv4 addresses of the range. ```APIDOC ## ipV4ToCIDR(ip_from, ip_to) ### Description Convert IPv4 range into a list of IPv4 CIDR notation. ### Parameters #### Path Parameters - **ip_from** (str) - Required - The starting IPv4 address in the range. - **ip_to** (str) - Required - The ending IPv4 address in the range. ### Returns - array - The list of IPv4 CIDR notation. ``` -------------------------------- ### Asynchronous Get All Geolocation Fields Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/ip2location-class.md Use getAllAsync to asynchronously retrieve all available geolocation fields for a given IP address. This method returns a Promise. ```javascript const result = await db.getAllAsync('1.1.1.1'); ``` -------------------------------- ### IP2Location Class Core Methods Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/INDEX.md Demonstrates the core methods for opening, closing, and querying the local IP2Location database. ```javascript IP2Location (Local Database) ├── Core: open, openAsync, close, closeAsync ├── Query: geoQuery, geoQueryAsync, getAll, getAllAsync ├── Fields: getCountryShort, getCity, getISP, ... (28 getters) ├── Meta: getAPIVersion, getDatabaseVersion, getPackageVersion └── Express: middleware() → See: ip2location-class.md ``` -------------------------------- ### Loading IP2Location Configuration from Environment Variables Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/configuration-and-examples.md Use the 'dotenv' package to load environment variables and initialize IP2Location database and web service clients. Ensure the .env file is correctly placed and variables are set. ```javascript require('dotenv').config(); const { IP2Location, IP2LocationWebService } = require('ip2location-nodejs'); // Load from environment const binPath = process.env.IP2LOCATION_BIN_PATH; const wsKey = process.env.IP2LOCATION_WS_KEY; const wsPackage = process.env.IP2LOCATION_WS_PACKAGE; const db = new IP2Location(); db.open(binPath); const ws = new IP2LocationWebService(); ws.open(wsKey, wsPackage); ``` -------------------------------- ### cidrToIPV4(cidr) Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/iptools-class.md Converts an IPv4 CIDR notation string into its corresponding start and end IPv4 address range. Returns null if the CIDR format is invalid. ```APIDOC ## cidrToIPV4(cidr) ### Description Converts an IPv4 CIDR notation string (e.g., "192.168.0.0/24") into an array containing the starting and ending IPv4 addresses of that range. ### Method Signature ```javascript cidrToIPV4(cidr: string): [string, string] | null ``` ### Parameters #### Path Parameters - **cidr** (string) - Required - The IPv4 CIDR notation string. ### Returns - **[string, string]** - An array where the first element is the start IP address and the second element is the end IP address of the range. - **null** - If the input `cidr` string is not a valid IPv4 CIDR notation (e.g., does not contain exactly one '/', has an invalid IPv4 address, or an invalid prefix length between 0-32). ### Example ```javascript const [start, end] = tools.cidrToIPV4('192.168.0.0/24'); console.log(start); // "192.168.0.0" console.log(end); // "192.168.0.255" const [start2, end2] = tools.cidrToIPV4('10.0.0.0/30'); console.log(start2); // "10.0.0.0" console.log(end2); // "10.0.0.3" ``` ``` -------------------------------- ### Convert IPv4 Range to CIDR Notation Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/quick-reference.md Converts a given IPv4 address range (start and end IP) into CIDR (Classless Inter-Domain Routing) notation. ```javascript // IPv4 const cidrs = tools.ipV4ToCIDR('192.168.0.0', '192.168.1.255'); ``` -------------------------------- ### CIDR Block Generation and Parsing Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/iptools-class.md Generates CIDR blocks for a given IP address range and converts CIDR notation back to start and end IP addresses. ```javascript // Generate all CIDR blocks for a range const cidrs = tools.ipV4ToCIDR('192.168.0.0', '192.168.1.255'); cidrs.forEach(cidr => { const [start, end] = tools.cidrToIPV4(cidr); console.log(`Block: ${cidr}, Range: ${start} - ${end}`); }); ``` -------------------------------- ### openAsync(binPath) Source: https://github.com/ip2location/ip2location-nodejs/blob/master/docs/source/code.md Loads the IP2Location BIN database asynchronously. This method is suitable for non-blocking operations and requires the file path to the BIN database. ```APIDOC ### openAsync(binPath) Load the IP2Location BIN database for lookup asynchronously. * **Parameters:** **binPath** (*str*) – (Required) The file path links to IP2Location BIN databases. This method asynchronously loads the specified IP2Location BIN database file, allowing your application to continue processing while the database is being loaded. ``` -------------------------------- ### IP2Location Constructor Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/ip2location-class.md Creates a new IP2Location instance. No parameters are required, and it initializes the instance with uninitialized database metadata. ```APIDOC ## Constructor ```javascript new IP2Location() ``` ### Description No parameters required. Creates a new IP2Location instance with uninitialized database metadata. ``` -------------------------------- ### cidrToIPV6(cidr) Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/iptools-class.md Converts an IPv6 CIDR notation string into its corresponding start and end IPv6 address range in expanded notation. Returns null if the CIDR format is invalid. ```APIDOC ## cidrToIPV6(cidr) ### Description Converts an IPv6 CIDR notation string (e.g., "2001:db8::/32") into an array containing the starting and ending IPv6 addresses of that range, represented in expanded notation. ### Method Signature ```javascript cidrToIPV6(cidr: string): [string, string] | null ``` ### Parameters #### Path Parameters - **cidr** (string) - Required - The IPv6 CIDR notation string. ### Returns - **[string, string]** - An array where the first element is the start IP address and the second element is the end IP address of the range, both in expanded IPv6 notation. - **null** - If the input `cidr` string is not a valid IPv6 CIDR notation (e.g., does not contain exactly one '/', has an invalid IPv6 address, or an invalid prefix length between 0-128). ### Example ```javascript const [start, end] = tools.cidrToIPV6('2001:db8::/32'); console.log(start); // "2001:db8:0:0:0:0:0:0" console.log(end); // "2001:db8:ffff:ffff:ffff:ffff:ffff:ffff" ``` ``` -------------------------------- ### Express.js Middleware for Geolocation Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/README.md Provides an example of integrating IP2Location into an Express.js application using middleware. This automatically detects the client's IP and attaches geolocation data to the request object. ```javascript const app = express(); const db = new IP2Location(); db.open('./IP2LOCATION-LITE-DB1.BIN'); // Automatic IP detection and geolocation app.use(db.middleware()); app.get('/', (req, res) => { res.json({ country: req.ip2location.countryLong, city: req.ip2location.city, status: req.ip2location.status }); }); ``` -------------------------------- ### Combined Workflow for Enriching Geodata Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/country-region-classes.md Illustrates a comprehensive workflow initializing IP2Location, Country, and Region components to enrich IP address data with country and region details. ```javascript const { Country, Region, IP2Location } = require('ip2location-nodejs'); async function enrichGeodata() { // Initialize all components const db = new IP2Location(); const country = new Country('./countries.csv'); const region = new Region('./regions.csv'); db.open('./IP2LOCATION-LITE-DB1.BIN'); // Look up IP const ip = '1.2.3.4'; const geoData = db.getAll(ip); // Enrich with country info const countryInfo = await country.getCountryInfo(geoData.countryShort); const regionCode = await region.getRegionCode( geoData.countryShort, geoData.region ); const enriched = { ip: geoData.ip, country: geoData.countryLong, countryInfo: countryInfo[0], region: geoData.region, regionCode: regionCode, city: geoData.city, latitude: geoData.latitude, longitude: geoData.longitude }; console.log(JSON.stringify(enriched, null, 2)); db.close(); } enrichGeodata().catch(console.error); ``` -------------------------------- ### Web Service Lookup with Addon Parameters Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/configuration-and-examples.md Perform a web service lookup and request additional data fields by specifying addon parameters. Ensure your subscription package supports the requested addons. ```javascript const { IP2LocationWebService } = require('ip2location-nodejs'); const ws = new IP2LocationWebService(); // Initialize with API key ws.open('YOUR_API_KEY', 'WS1', true); // useSSL=true ws.lookup('8.8.8.8', 'continent,country,state,city,geotargeting,language', 'en', (error, result) => { console.log(result); }); ``` -------------------------------- ### IP2Location Class Instantiation Source: https://github.com/ip2location/ip2location-nodejs/blob/master/docs/source/code.md Constructs an instance of the IP2Location Class. This is the first step to using the library's functionalities. ```APIDOC ## IP2Location Class ### *class* IP2Location Construct the IP2Location Class. This is the entry point for using the IP2Location Node.js library. Instantiate this class to access its methods for database operations and IP lookups. ``` -------------------------------- ### Expand and Compress IPv6 Addresses Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/quick-reference.md Demonstrates the expansion of a compressed IPv6 address to its full form and the compression of a full IPv6 address. ```javascript const expanded = tools.expandIPV6('::1'); const compressed = tools.compressIPV6('2001:0db8:0000:0000:0000:0000:0000:0001'); ``` -------------------------------- ### Web Service IP Lookup Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/quick-reference.md Perform IP lookups using the IP2Location Web Service. Ensure you have a valid API key and service type. This example demonstrates a basic lookup with error handling and console logging of results. ```javascript const ws = new IP2LocationWebService(); ws.open('KEY', 'WS1'); ws.lookup(ip, 'continent,country', 'en', (err, data) => { if (err) return handleError(err); console.log(data); }); ``` -------------------------------- ### Query IP2Location Web Service Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/quick-reference.md Shows how to initialize the Web Service client, perform an IP lookup, and check remaining credits. Requires an API key and API type. ```javascript const ws = new IP2LocationWebService(); ws.open('ABCDEF1234', 'WS1'); ws.lookup('8.8.8.8', '', '', (error, result) => { if (error) console.error(error); else console.log(result); }); ws.getCredit((error, result) => { console.log('Remaining:', result.credits_remaining); }); ``` -------------------------------- ### Get Region Code by Country and Region Name Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/country-region-classes.md Retrieve a standardized region code using the country code and region name. The method handles asynchronous parsing, trims input, and performs case-insensitive matching. Returns null if no match is found. ```javascript const region = new Region('./regions.csv'); // Get region code (case-insensitive matching) const code1 = await region.getRegionCode('US', 'California'); console.log('CA code:', code1); // e.g., "CA" // Get region code with different case const code2 = await region.getRegionCode('US', 'texas'); console.log('TX code:', code2); // e.g., "TX" // Trimmed input const code3 = await region.getRegionCode(' us ', ' new york '); console.log('NY code:', code3); // e.g., "NY" // Non-existent country or region returns null const code4 = await region.getRegionCode('US', 'NonExistent'); console.log('Not found:', code4); // null ``` -------------------------------- ### Convert IPv4 Range to CIDR Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/iptools-class.md Converts a given IPv4 address range into a minimal set of non-overlapping CIDR notation entries. Accepts start and end IPv4 addresses as strings. Returns an array of CIDR strings or null if the input is invalid. ```javascript const cidrs = tools.ipV4ToCIDR('192.168.1.0', '192.168.1.255'); console.log(cidrs); // ["192.168.1.0/24"] const cidrs2 = tools.ipV4ToCIDR('192.168.0.0', '192.168.1.255'); console.log(cidrs2); // ["192.168.0.0/23"] ``` -------------------------------- ### lookup(myIP, addOn, lang, callback) Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/ip2locationwebservice-class.md Queries the IP2Location Web Service for geolocation data on an IP address. It takes the IP address, optional addon data fields, an optional language code, and a callback function as parameters. The results are passed to the callback function. ```APIDOC ## lookup(myIP, addOn, lang, callback) ### Description Queries the IP2Location Web Service for geolocation data on an IP address. It takes the IP address, optional addon data fields, an optional language code, and a callback function as parameters. The results are passed to the callback function. ### Method POST ### Endpoint api.ip2location.com/v2/ ### Parameters #### Query Parameters - **key** (string) - Required - API key - **package** (string) - Required - Package name - **ip** (string) - Required - IP address to query - **addon** (string) - Optional - Comma-separated addon data fields (e.g., "continent,country,state,city") - **lang** (string) - Optional - Language code for results (e.g., "en", "zh-cn") ### Request Example ```javascript { "example": "ws.lookup('8.8.8.8', 'continent,country,state,city', 'en', (error, result) => { ... });" } ``` ### Response #### Success Response (200) - **countryShort** (string) - Country short name - **countryLong** (string) - Country long name - **state** (string) - State/Province name - **city** (string) - City name - **latitude** (number) - Latitude coordinate - **longitude** (number) - Longitude coordinate - **api_code** (string) - API response code - **api_message** (string) - API response message #### Response Example ```json { "example": "{\"country_short\": \"US\", \"country_long\": \"United States\", \"state\": \"California\", \"city\": \"Mountain View\", \"latitude\": 37.422, \"longitude\": -122.084, \"api_code\": \"OK\", \"api_message\": \"OK\"}" } ``` ``` -------------------------------- ### Geolocation Lookup with Local Database and Cloud API Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/README.md Demonstrates how to perform geolocation lookups using a local database for offline access and the Cloud API for real-time results. Ensure the local database file is available or an API key is configured for the Cloud API. ```javascript // Local database (fastest, offline) const db = new IP2Location(); db.open('./IP2LOCATION-LITE-DB1.BIN'); const result = db.getAll('8.8.8.8'); // Cloud API (real-time, no setup) const ws = new IP2LocationWebService(); ws.open('API_KEY', 'WS1'); ws.lookup('8.8.8.8', '', '', (err, result) => { ... }); ``` -------------------------------- ### Region Class Constructor Source: https://github.com/ip2location/ip2location-nodejs/blob/master/docs/source/code.md Initializes the Ip2locationRegion class by loading the IP2Location ISO 3166-2 Subdivision Code CSV file. The CSV file is required for the class to function correctly. ```APIDOC ## class Region(csvFilePath) ### Description Initiate Ip2locationRegion class and load the IP2Location ISO 3166-2 Subdivision Code CSV file. ### Parameters #### Path Parameters * **csvFilePath** (str) - Required - The file path links to IP2Location ISO 3166-2 Subdivision Code CSV file. ``` -------------------------------- ### Country Constructor Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/country-region-classes.md Initializes the Country class by loading country information from a specified CSV file. Asynchronous parsing begins immediately. ```APIDOC ## Constructor Country ### Description Initializes the Country class by loading country information from a specified CSV file. Asynchronous parsing begins immediately. ### Signature ```javascript new Country(csvFile: string) ``` ### Parameters #### Path Parameters - **csvFile** (string) - Required - Full or relative path to country information CSV file ### Throws - `Error: "The CSV file is not found."` - File does not exist - `Error: "Invalid country information CSV file."` - CSV structure invalid - `Error: "Unable to read ."` - File read error ### Example ```javascript const { Country } = require('ip2location-nodejs'); try { const country = new Country('./countries.csv'); // Note: parsing happens asynchronously, use await getCountryInfo() } catch (err) { console.error('Failed to initialize Country:', err.message); } ``` ``` -------------------------------- ### IP2LocationWebService Constructor Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/ip2locationwebservice-class.md Initializes a new instance of the IP2LocationWebService client without any credentials. This client is used to interact with the IP2Location REST API. ```APIDOC ## Constructor ```javascript new IP2LocationWebService() ``` No parameters required. Creates a new web service client instance without credentials. ``` -------------------------------- ### Handle Missing Database File Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/errors-and-validation.md Catches errors when the database file is not initialized, has been closed, or no longer exists. Ensures the database is loaded before querying. ```javascript const db = new IP2Location(); const result = db.getAll('8.8.8.8'); // No file opened console.log(result.city); // "MISSING_FILE" ``` -------------------------------- ### Test Fixtures Directory Structure Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/configuration-and-examples.md Organize test BIN files and supporting CSV data in a dedicated 'test/fixtures' directory. This structure helps in maintaining a clean and organized testing environment. ```tree test/ ├── fixtures/ │ ├── IP2LOCATION-LITE-DB1.BIN │ ├── countries.csv │ └── regions.csv └── geoip.test.js ``` -------------------------------- ### Load and Query Region Data from CSV Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/quick-reference.md Demonstrates loading region data from a CSV file and retrieving a region's code based on country and region name. ```javascript const region = new Region('./regions.csv'); const caCode = await region.getRegionCode('US', 'California'); ``` -------------------------------- ### Configure HTTP Protocol Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/ip2locationwebservice-class.md Set the `useSSL` parameter to `false` in the `open()` method to use HTTP on port 80 instead of the default HTTPS. ```javascript ws.open('ABCDEF1234', 'WS1', false); ``` -------------------------------- ### Initialize Country Class Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/country-region-classes.md Instantiate the Country class with the path to the country information CSV file. The constructor initiates asynchronous CSV parsing. Ensure the CSV file exists and is correctly formatted. ```javascript const { Country } = require('ip2location-nodejs'); try { const country = new Country('./countries.csv'); // Note: parsing happens asynchronously, use await getCountryInfo() } catch (err) { console.error('Failed to initialize Country:', err.message); } ``` -------------------------------- ### Error Handling: No Records Available Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/country-region-classes.md Shows how to catch errors when attempting to retrieve information for a non-existent record using methods like getCountryInfo(). ```javascript try { const info = await country.getCountryInfo('XX'); } catch (err) { console.error(err.message); // "No record available." } ``` -------------------------------- ### binaryToIP(myBin) Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/iptools-class.md Converts a 128-bit binary string back to its IPv6 address representation. Returns null if the binary string is invalid. ```APIDOC ## binaryToIP(myBin) ### Description Converts a 128-bit binary string back to an IPv6 address in compressed notation. This is the inverse operation of `ipToBinary`. ### Method Signature ```javascript binaryToIP(myBin: string): string | null ``` ### Parameters #### Path Parameters - **myBin** (string) - Required - 128-character binary string (composed of only '0' and '1') ### Returns - **string** - The IPv6 address in compressed notation if the conversion is successful. - **null** - If the input `myBin` is an invalid binary string format (not 1-128 characters, or contains characters other than '0' and '1'). ### Example ```javascript const binary = '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001'; const ip = tools.binaryToIP(binary); console.log(ip); // "::1" ``` ``` -------------------------------- ### Region Class Query Method Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/INDEX.md Illustrates querying region-specific information with the Region class. ```javascript Region (CSV Loader) └── Query: getRegionCode(country?, region?) → See: country-region-classes.md ``` -------------------------------- ### Environment Variables for IP2Location Source: https://github.com/ip2location/ip2location-nodejs/blob/master/_autodocs/configuration-and-examples.md Configure IP2Location settings by defining environment variables in a .env file. This includes the path to the database file and your API key for web services. ```bash # .env file IP2LOCATION_BIN_PATH=./databases/IP2LOCATION-LITE-DB1.BIN IP2LOCATION_WS_KEY=YOUR_API_KEY IP2LOCATION_WS_PACKAGE=WS1 ``` -------------------------------- ### Country Class Initialization Source: https://github.com/ip2location/ip2location-nodejs/blob/master/docs/source/code.md Initiates the Ip2locationCountry class by loading the IP2Location Country Information CSV file. This database can be downloaded for free. ```APIDOC ## class Country(csvFilePath) ### Description Initiates the Ip2locationCountry class and loads the IP2Location Country Information CSV file. ### Parameters #### Path Parameters - **csvFilePath** (str) - Required - The file path links to IP2Location Country Information CSV file. ```