librats
v0.5.2
Published
Node.js bindings for librats - A high-performance peer-to-peer networking library
Maintainers
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 libratsThe installation process will automatically:
- Download all necessary source files
- Build the native librats library using CMake
- Build the Node.js native addon
- 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-essentialandcmakepackagessudo 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 verifyThis 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 buildQuick 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 clientstop(): void- Stop the clientconnect(host: string, port: number): boolean- Connect to a peerconnectWithStrategy(host: string, port: number, strategy: number): boolean- Connect with specific strategydisconnect(peerId: string): void- Disconnect from a peer
Messaging
sendString(peerId: string, message: string): boolean- Send string messagesendBinary(peerId: string, data: Buffer): boolean- Send binary datasendJson(peerId: string, jsonStr: string): boolean- Send JSON databroadcastString(message: string): number- Broadcast string to all peersbroadcastBinary(data: Buffer): number- Broadcast binary to all peersbroadcastJson(jsonStr: string): number- Broadcast JSON to all peers
Information
getPeerCount(): number- Get number of connected peersgetOurPeerId(): string | null- Get our peer IDgetPeerIds(): string[]- Get list of connected peer IDsgetConnectionStatistics(): string | null- Get connection statistics as JSON
File Transfer
sendFile(peerId: string, filePath: string, remoteFilename?: string): string | null- Send filesendDirectory(peerId: string, dirPath: string, remoteDirName?: string, recursive?: boolean): string | null- Send directoryrequestFile(peerId: string, remoteFilePath: string, localPath: string): string | null- Request filerequestDirectory(peerId: string, remoteDirPath: string, localDirPath: string, recursive?: boolean): string | null- Request directoryacceptFileTransfer(transferId: string, localPath: string): boolean- Accept file transferrejectFileTransfer(transferId: string, reason?: string): boolean- Reject file transfercancelFileTransfer(transferId: string): boolean- Cancel file transferpauseFileTransfer(transferId: string): boolean- Pause file transferresumeFileTransfer(transferId: string): boolean- Resume file transfer
GossipSub
isGossipsubAvailable(): boolean- Check if GossipSub is availablesubscribeToTopic(topic: string): boolean- Subscribe to topicunsubscribeFromTopic(topic: string): boolean- Unsubscribe from topicpublishToTopic(topic: string, message: string): boolean- Publish messagepublishJsonToTopic(topic: string, jsonStr: string): boolean- Publish JSONgetSubscribedTopics(): string[]- Get subscribed topicsgetTopicPeers(topic: string): string[]- Get peers in topic
DHT
startDhtDiscovery(dhtPort: number): boolean- Start DHT discoverystopDhtDiscovery(): void- Stop DHT discoveryisDhtRunning(): boolean- Check if DHT is runningannounceForHash(contentHash: string, port: number, callback?: (peers: string[]) => void): boolean- Announce for hash with optional peer discovery callback
Encryption
setEncryptionEnabled(enabled: boolean): boolean- Enable/disable encryptionisEncryptionEnabled(): boolean- Check if encryption is enabledgenerateEncryptionKey(): string | null- Generate new encryption keysetEncryptionKey(keyHex: string): boolean- Set encryption keygetEncryptionKey(): string | null- Get current encryption key
Event Handlers
onConnection(callback: (peerId: string) => void): void- Set connection callbackonString(callback: (peerId: string, message: string) => void): void- Set string message callbackonBinary(callback: (peerId: string, data: Buffer) => void): void- Set binary message callbackonJson(callback: (peerId: string, jsonStr: string) => void): void- Set JSON message callbackonDisconnect(callback: (peerId: string) => void): void- Set disconnect callbackonFileProgress(callback: (transferId: string, progressPercent: number, status: string) => void): void- Set file progress callback
Utility Functions
getVersionString(): string- Get librats version stringgetVersion(): VersionInfo- Get version componentsgetGitDescribe(): string- Get git describe stringgetAbi(): number- Get ABI version
Constants
ConnectionStrategy
ConnectionStrategy.DIRECT_ONLY- Direct connection onlyConnectionStrategy.STUN_ASSISTED- STUN-assisted connectionConnectionStrategy.ICE_FULL- Full ICE negotiationConnectionStrategy.TURN_RELAY- TURN relay connectionConnectionStrategy.AUTO_ADAPTIVE- Automatic strategy selection
ErrorCodes
ErrorCodes.SUCCESS- Operation successfulErrorCodes.INVALID_HANDLE- Invalid client handleErrorCodes.INVALID_PARAMETER- Invalid parameterErrorCodes.NOT_RUNNING- Client not runningErrorCodes.OPERATION_FAILED- Operation failedErrorCodes.PEER_NOT_FOUND- Peer not foundErrorCodes.MEMORY_ALLOCATION- Memory allocation errorErrorCodes.JSON_PARSE- JSON parsing error
Examples
The examples/ directory contains comprehensive examples:
basic_client.js- Basic peer-to-peer networking and messagingfile_transfer.js- File and directory transfer with interactive CLIgossipsub_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 AliceTesting
Run the test suite:
npm testOr run the simple test script:
node test/test.jsBuilding from Source
Debug Build
npm run buildClean Build
npm run clean
npm run buildTypeScript 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
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- 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-toolsLinux: Install build dependencies
sudo apt install build-essential python3macOS: Install Xcode Command Line Tools
xcode-select --installRuntime 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.jsSupport
For more advanced usage, see the C API documentation and the main project README.
