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

iptoasn-node

v0.9.0

Published

High-performance IP to ASN lookup library with automatic updates (Rust-powered)

Readme

iptoasn-node

High-performance IP to ASN (Autonomous System Number) lookup library powered by Rust

A blazingly fast Node.js library for looking up IP addresses and their associated ASN information. Built with Rust using NAPI-RS for optimal performance with automatic database updates.

🚀 Features

  • Ultra-fast lookups - Microsecond-level performance with binary search in native code
  • 🔄 Automatic updates - Background task periodically checks for new data
  • 🌍 IPv4 and IPv6 - Full support for both IP versions
  • 💾 Smart caching - Efficient HTTP conditional requests (ETag/Last-Modified)
  • 🛡️ Zero-downtime - Hot-swaps database without interrupting service
  • 🦀 Rust-powered - Native performance with memory safety
  • 📦 Easy to use - Simple async/sync API
  • 🎯 TypeScript - Full type definitions included

📦 Installation

npm install iptoasn-node
# or
yarn add iptoasn-node
# or
pnpm add iptoasn-node

🎯 Quick Start

const { IpToAsn } = require("iptoasn-node");

async function main() {
  // Create database instance
  const db = new IpToAsn(
    "https://iptoasn.com/data/ip2asn-combined.tsv.gz",
    "./cache"
  );

  // Load database (downloads if needed, or loads from cache)
  await db.load();

  // Fast synchronous lookups!
  const result = db.lookup("8.8.8.8");
  console.log(result);
  // {
  //   ip: '8.8.8.8',
  //   announced: true,
  //   asNumber: 15169,
  //   asCountryCode: 'US',
  //   asDescription: 'GOOGLE',
  //   firstIp: '8.8.8.0',
  //   lastIp: '8.8.8.255'
  // }

  // Start automatic updates (every 60 minutes)
  await db.startAutoUpdate(60);
}

main();

📖 API Documentation

Class: IpToAsn

new IpToAsn(url, cacheDir)

Create a new database instance.

  • url string - Database URL (HTTP/HTTPS or file://)
  • cacheDir string - Directory for caching downloaded databases
const db = new IpToAsn(
  "https://iptoasn.com/data/ip2asn-combined.tsv.gz",
  "./cache"
);

async load()

Load the database (initial load or manual refresh). Downloads if needed, or loads from cache.

await db.load();

lookup(ip)AsnResult

Look up an IP address. Synchronous and very fast (microseconds).

  • ip string - IPv4 or IPv6 address
  • Returns AsnResult - ASN information
const result = db.lookup("1.1.1.1");

AsnResult:

{
  ip: string;
  announced: boolean;
  firstIp?: string;
  lastIp?: string;
  asNumber?: number;
  asCountryCode?: string;
  asDescription?: string;
}

stats()DatabaseStats

Get database statistics.

const stats = db.stats();
console.log(`${stats.recordCount} records loaded`);

DatabaseStats:

{
  recordCount: number;
  lastUpdateTimestamp?: number; // Unix timestamp in seconds
}

async startAutoUpdate(intervalMinutes)

Start automatic database updates in the background.

  • intervalMinutes number - How often to check for updates

The updater uses HTTP conditional requests (ETag/Last-Modified) to avoid unnecessary downloads.

// Check for updates every hour
await db.startAutoUpdate(60);

stopAutoUpdate()

Stop automatic database updates.

db.stopAutoUpdate();

async forceUpdate()boolean

Force an immediate database update check.

  • Returns boolean - Whether database was updated
const updated = await db.forceUpdate();

🌐 Express Server Example

const express = require("express");
const { IpToAsn } = require("iptoasn-node");

const app = express();
const db = new IpToAsn(
  "https://iptoasn.com/data/ip2asn-combined.tsv.gz",
  "./cache"
);

// Initialize
await db.load();
await db.startAutoUpdate(60);

// API endpoint
app.get("/v1/as/ip/:ip", (req, res) => {
  try {
    const result = db.lookup(req.params.ip);
    if (result.announced) {
      res.json(result);
    } else {
      res.status(404).json({ ip: req.params.ip, announced: false });
    }
  } catch (error) {
    res.status(400).json({ error: "Invalid IP address" });
  }
});

app.listen(3000);

🏗️ Architecture

┌─────────────────────────────────────┐
│      Node.js Application            │
│   (Your Express/Fastify server)     │
└──────────────┬──────────────────────┘
               │
        ┌──────▼──────┐
        │  NAPI-RS    │  ← Native bindings
        │  Bindings   │
        └──────┬──────┘
               │
    ┌──────────▼──────────────┐
    │   Rust Core Library     │
    │  - Binary search O(log n)│
    │  - String interning      │
    │  - Background updates    │
    │  - Smart HTTP caching    │
    └─────────────────────────┘

⚡ Performance

  • Lookup time: ~1-10 microseconds per lookup
  • Memory usage: ~200-300MB for 670K+ records
  • Update time: Hot-swap in milliseconds
  • Zero GC pressure: Data lives in Rust heap

🔄 How Updates Work

  1. Background task checks for updates at specified interval
  2. Conditional request sent with ETag/Last-Modified headers
  3. If 304 Not Modified returned, no download needed
  4. If new data available:
    • Downloads and decompresses in memory
    • Parses TSV format
    • Hot-swaps database atomically
    • Old data cleaned up automatically
  5. Zero downtime - lookups continue during updates

🛡️ Error Handling

The library handles errors gracefully:

  • Network failures → Falls back to cached data
  • Parse errors → Keeps existing database
  • Invalid IPs → Returns error via exception
try {
  const result = db.lookup("not-an-ip");
} catch (error) {
  console.error("Invalid IP:", error.message);
}

📊 Data Source

This library uses the IP to ASN database from iptoasn.com, which provides:

  • IPv4 and IPv6 address ranges
  • ASN numbers and descriptions
  • Country codes
  • Regular updates

🔧 Environment Variables

DATABASE_URL=https://iptoasn.com/data/ip2asn-combined.tsv.gz
CACHE_DIR=./cache
UPDATE_INTERVAL=60  # minutes
RUST_LOG=info       # Rust logging level

🏗️ Building from Source

# Install dependencies
npm install

# Build native module
npm run build

# Build for production
npm run build:release

📝 TypeScript

Full TypeScript definitions are included:

import { IpToAsn, AsnResult, DatabaseStats } from "iptoasn-node";

const db = new IpToAsn(url, cacheDir);
const result: AsnResult = db.lookup("8.8.8.8");

🤝 Contributing

Contributions are welcome! Please see the main repository for contribution guidelines.

📄 License

MIT License - see LICENSE file for details.

🙏 Credits

🔗 Links