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 🙏

© 2025 – Pkg Stats / Ryan Hefner

librats

v0.5.2

Published

Node.js bindings for librats - A high-performance peer-to-peer networking library

Readme

LibRats Node.js Bindings

Node.js bindings for librats - A high-performance peer-to-peer networking library with support for DHT, GossipSub, file transfer, NAT traversal, and more.

Features

  • Peer-to-peer networking - Direct connections between peers
  • DHT (Distributed Hash Table) - Decentralized peer discovery
  • GossipSub - Topic-based publish/subscribe messaging
  • File Transfer - Send and receive files and directories
  • mDNS Discovery - Local network peer discovery
  • NAT Traversal - STUN/ICE support for connecting through firewalls
  • Encryption - End-to-end encryption using Noise protocol
  • Message Exchange - String, binary, and JSON message types
  • Configuration Persistence - Save and restore client settings

Installation

Quick Install

Install directly from npm:

npm install librats

The installation process will automatically:

  1. Download all necessary source files
  2. Build the native librats library using CMake
  3. Build the Node.js native addon
  4. Set up the bindings

No additional build steps required!

Prerequisites

The following build tools are required and will be used automatically during installation:

  • Node.js: 20.0.0 or higher
  • CMake: Version 3.10 or higher (download here)
  • C++ Compiler and Build Tools:
    • Windows: Visual Studio Build Tools 2017 or later (download here)
    • Linux: build-essential and cmake packages
      sudo apt install build-essential cmake
    • macOS: Xcode Command Line Tools
      xcode-select --install

Verifying Installation

After installation, you can verify everything is working:

npm run verify

This will check that the native addon is built correctly and all features are available.

Building from Source

If you're developing or need to rebuild:

# Clone the repository
git clone https://github.com/librats/librats.git
cd librats/nodejs

# Install (builds everything automatically)
npm install

# Verify the installation
npm run verify

# Or build manually
npm run build

Quick Start

Basic Example

const { RatsClient, ConnectionStrategy } = require('librats');

// Create a client listening on port 8080
const client = new RatsClient(8080);

// Set up event handlers
client.onConnection((peerId) => {
  console.log(`Peer connected: ${peerId}`);
  client.sendString(peerId, 'Hello from Node.js!');
});

client.onString((peerId, message) => {
  console.log(`Received: ${message} from ${peerId}`);
});

// Start the client
client.start();

// Connect to another peer
client.connect('127.0.0.1', 8081);

File Transfer Example

const { RatsClient } = require('librats');

const client = new RatsClient(8080);

// Set up file transfer progress monitoring
client.onFileProgress((transferId, progressPercent, status) => {
  console.log(`Transfer ${transferId}: ${progressPercent}% - ${status}`);
});

client.start();

// Send a file to a peer
const transferId = client.sendFile('peer_id_here', './myfile.txt', 'remote_file.txt');
console.log(`File transfer started: ${transferId}`);

GossipSub Chat Example

const { RatsClient } = require('librats');

const client = new RatsClient(8080);
client.start();

// Subscribe to a topic
client.subscribeToTopic('general-chat');

// Publish a message
const message = {
  type: 'chat',
  username: 'Alice',
  message: 'Hello everyone!',
  timestamp: Date.now()
};

client.publishJsonToTopic('general-chat', JSON.stringify(message));

API Reference

RatsClient

Constructor

  • new RatsClient(listenPort: number) - Create a new client instance

Basic Operations

  • start(): boolean - Start the client
  • stop(): void - Stop the client
  • connect(host: string, port: number): boolean - Connect to a peer
  • connectWithStrategy(host: string, port: number, strategy: number): boolean - Connect with specific strategy
  • disconnect(peerId: string): void - Disconnect from a peer

Messaging

  • sendString(peerId: string, message: string): boolean - Send string message
  • sendBinary(peerId: string, data: Buffer): boolean - Send binary data
  • sendJson(peerId: string, jsonStr: string): boolean - Send JSON data
  • broadcastString(message: string): number - Broadcast string to all peers
  • broadcastBinary(data: Buffer): number - Broadcast binary to all peers
  • broadcastJson(jsonStr: string): number - Broadcast JSON to all peers

Information

  • getPeerCount(): number - Get number of connected peers
  • getOurPeerId(): string | null - Get our peer ID
  • getPeerIds(): string[] - Get list of connected peer IDs
  • getConnectionStatistics(): string | null - Get connection statistics as JSON

File Transfer

  • sendFile(peerId: string, filePath: string, remoteFilename?: string): string | null - Send file
  • sendDirectory(peerId: string, dirPath: string, remoteDirName?: string, recursive?: boolean): string | null - Send directory
  • requestFile(peerId: string, remoteFilePath: string, localPath: string): string | null - Request file
  • requestDirectory(peerId: string, remoteDirPath: string, localDirPath: string, recursive?: boolean): string | null - Request directory
  • acceptFileTransfer(transferId: string, localPath: string): boolean - Accept file transfer
  • rejectFileTransfer(transferId: string, reason?: string): boolean - Reject file transfer
  • cancelFileTransfer(transferId: string): boolean - Cancel file transfer
  • pauseFileTransfer(transferId: string): boolean - Pause file transfer
  • resumeFileTransfer(transferId: string): boolean - Resume file transfer

GossipSub

  • isGossipsubAvailable(): boolean - Check if GossipSub is available
  • subscribeToTopic(topic: string): boolean - Subscribe to topic
  • unsubscribeFromTopic(topic: string): boolean - Unsubscribe from topic
  • publishToTopic(topic: string, message: string): boolean - Publish message
  • publishJsonToTopic(topic: string, jsonStr: string): boolean - Publish JSON
  • getSubscribedTopics(): string[] - Get subscribed topics
  • getTopicPeers(topic: string): string[] - Get peers in topic

DHT

  • startDhtDiscovery(dhtPort: number): boolean - Start DHT discovery
  • stopDhtDiscovery(): void - Stop DHT discovery
  • isDhtRunning(): boolean - Check if DHT is running
  • announceForHash(contentHash: string, port: number, callback?: (peers: string[]) => void): boolean - Announce for hash with optional peer discovery callback

Encryption

  • setEncryptionEnabled(enabled: boolean): boolean - Enable/disable encryption
  • isEncryptionEnabled(): boolean - Check if encryption is enabled
  • generateEncryptionKey(): string | null - Generate new encryption key
  • setEncryptionKey(keyHex: string): boolean - Set encryption key
  • getEncryptionKey(): string | null - Get current encryption key

Event Handlers

  • onConnection(callback: (peerId: string) => void): void - Set connection callback
  • onString(callback: (peerId: string, message: string) => void): void - Set string message callback
  • onBinary(callback: (peerId: string, data: Buffer) => void): void - Set binary message callback
  • onJson(callback: (peerId: string, jsonStr: string) => void): void - Set JSON message callback
  • onDisconnect(callback: (peerId: string) => void): void - Set disconnect callback
  • onFileProgress(callback: (transferId: string, progressPercent: number, status: string) => void): void - Set file progress callback

Utility Functions

  • getVersionString(): string - Get librats version string
  • getVersion(): VersionInfo - Get version components
  • getGitDescribe(): string - Get git describe string
  • getAbi(): number - Get ABI version

Constants

ConnectionStrategy

  • ConnectionStrategy.DIRECT_ONLY - Direct connection only
  • ConnectionStrategy.STUN_ASSISTED - STUN-assisted connection
  • ConnectionStrategy.ICE_FULL - Full ICE negotiation
  • ConnectionStrategy.TURN_RELAY - TURN relay connection
  • ConnectionStrategy.AUTO_ADAPTIVE - Automatic strategy selection

ErrorCodes

  • ErrorCodes.SUCCESS - Operation successful
  • ErrorCodes.INVALID_HANDLE - Invalid client handle
  • ErrorCodes.INVALID_PARAMETER - Invalid parameter
  • ErrorCodes.NOT_RUNNING - Client not running
  • ErrorCodes.OPERATION_FAILED - Operation failed
  • ErrorCodes.PEER_NOT_FOUND - Peer not found
  • ErrorCodes.MEMORY_ALLOCATION - Memory allocation error
  • ErrorCodes.JSON_PARSE - JSON parsing error

Examples

The examples/ directory contains comprehensive examples:

  • basic_client.js - Basic peer-to-peer networking and messaging
  • file_transfer.js - File and directory transfer with interactive CLI
  • gossipsub_chat.js - Topic-based chat using GossipSub

Running Examples

# Basic client (listens on port 8080)
node examples/basic_client.js

# Basic client connecting to another peer
node examples/basic_client.js 8081 127.0.0.1 8080

# File transfer client
node examples/file_transfer.js 8080

# GossipSub chat
node examples/gossipsub_chat.js 8080 Alice

Testing

Run the test suite:

npm test

Or run the simple test script:

node test/test.js

Building from Source

Debug Build

npm run build

Clean Build

npm run clean
npm run build

TypeScript Support

Full TypeScript definitions are included. Import types:

import { RatsClient, ConnectionStrategy, ErrorCodes, VersionInfo } from 'librats';

const client: RatsClient = new RatsClient(8080);
client.start();

Error Handling

Most operations return boolean values indicating success/failure. For detailed error information, check the console output or use the statistics functions:

const stats = client.getConnectionStatistics();
if (stats) {
  const parsed = JSON.parse(stats);
  console.log('Connection stats:', parsed);
}

Performance Considerations

  • Use binary messages for large data transfers
  • Enable encryption only when needed (adds overhead)
  • Monitor file transfer progress for large files
  • Use appropriate connection strategies for your network environment

Platform Support

  • Windows - Requires Visual Studio Build Tools
  • Linux - Requires build-essential
  • macOS - Requires Xcode Command Line Tools
  • Android - Supported via native Android bindings (separate package)

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Submit a pull request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Troubleshooting

Build Issues

Windows: Ensure Visual Studio Build Tools are installed

npm install --global windows-build-tools

Linux: Install build dependencies

sudo apt install build-essential python3

macOS: Install Xcode Command Line Tools

xcode-select --install

Runtime Issues

Port already in use: Choose a different port or kill the process using the port

# Find process using port
netstat -tulpn | grep :8080

# Kill process
kill -9 <pid>

Permission denied: Run with appropriate permissions or use ports > 1024

Connection timeout: Check firewall settings and ensure peers are reachable

Debug Mode

Enable debug logging by setting environment variable:

export LIBRATS_DEBUG=1
node examples/basic_client.js

Support

For more advanced usage, see the C API documentation and the main project README.