librats 0.3.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +405 -405
  2. package/binding.gyp +96 -95
  3. package/lib/index.d.ts +522 -522
  4. package/lib/index.js +82 -82
  5. package/native-src/3rdparty/android/ifaddrs-android.c +600 -0
  6. package/native-src/3rdparty/android/ifaddrs-android.h +54 -0
  7. package/native-src/CMakeLists.txt +360 -0
  8. package/native-src/LICENSE +21 -0
  9. package/native-src/src/bencode.cpp +485 -0
  10. package/native-src/src/bencode.h +145 -0
  11. package/native-src/src/bittorrent.cpp +3682 -0
  12. package/native-src/src/bittorrent.h +731 -0
  13. package/native-src/src/dht.cpp +2342 -0
  14. package/native-src/src/dht.h +501 -0
  15. package/native-src/src/encrypted_socket.cpp +817 -0
  16. package/native-src/src/encrypted_socket.h +239 -0
  17. package/native-src/src/file_transfer.cpp +1808 -0
  18. package/native-src/src/file_transfer.h +567 -0
  19. package/native-src/src/fs.cpp +639 -0
  20. package/native-src/src/fs.h +108 -0
  21. package/native-src/src/gossipsub.cpp +1137 -0
  22. package/native-src/src/gossipsub.h +403 -0
  23. package/native-src/src/ice.cpp +1386 -0
  24. package/native-src/src/ice.h +328 -0
  25. package/native-src/src/json.hpp +25526 -0
  26. package/native-src/src/krpc.cpp +558 -0
  27. package/native-src/src/krpc.h +145 -0
  28. package/native-src/src/librats.cpp +2715 -0
  29. package/native-src/src/librats.h +1729 -0
  30. package/native-src/src/librats_bittorrent.cpp +167 -0
  31. package/native-src/src/librats_c.cpp +1317 -0
  32. package/native-src/src/librats_c.h +237 -0
  33. package/native-src/src/librats_encryption.cpp +123 -0
  34. package/native-src/src/librats_file_transfer.cpp +226 -0
  35. package/native-src/src/librats_gossipsub.cpp +293 -0
  36. package/native-src/src/librats_ice.cpp +515 -0
  37. package/native-src/src/librats_logging.cpp +158 -0
  38. package/native-src/src/librats_mdns.cpp +171 -0
  39. package/native-src/src/librats_nat.cpp +571 -0
  40. package/native-src/src/librats_persistence.cpp +815 -0
  41. package/native-src/src/logger.h +412 -0
  42. package/native-src/src/mdns.cpp +1178 -0
  43. package/native-src/src/mdns.h +253 -0
  44. package/native-src/src/network_utils.cpp +598 -0
  45. package/native-src/src/network_utils.h +162 -0
  46. package/native-src/src/noise.cpp +981 -0
  47. package/native-src/src/noise.h +227 -0
  48. package/native-src/src/os.cpp +371 -0
  49. package/native-src/src/os.h +40 -0
  50. package/native-src/src/rats_export.h +17 -0
  51. package/native-src/src/sha1.cpp +163 -0
  52. package/native-src/src/sha1.h +42 -0
  53. package/native-src/src/socket.cpp +1376 -0
  54. package/native-src/src/socket.h +309 -0
  55. package/native-src/src/stun.cpp +484 -0
  56. package/native-src/src/stun.h +349 -0
  57. package/native-src/src/threadmanager.cpp +105 -0
  58. package/native-src/src/threadmanager.h +53 -0
  59. package/native-src/src/tracker.cpp +1110 -0
  60. package/native-src/src/tracker.h +268 -0
  61. package/native-src/src/version.cpp +24 -0
  62. package/native-src/src/version.h.in +45 -0
  63. package/native-src/version.rc.in +31 -0
  64. package/package.json +62 -68
  65. package/scripts/build-librats.js +241 -194
  66. package/scripts/postinstall.js +52 -52
  67. package/scripts/prepare-package.js +187 -91
  68. package/scripts/verify-installation.js +119 -119
  69. package/src/librats_node.cpp +1174 -1174
package/README.md CHANGED
@@ -1,405 +1,405 @@
1
- # LibRats Node.js Bindings
2
-
3
- Node.js bindings for librats - A high-performance peer-to-peer networking library with support for DHT, GossipSub, file transfer, NAT traversal, and more.
4
-
5
- ## Features
6
-
7
- - **Peer-to-peer networking** - Direct connections between peers
8
- - **DHT (Distributed Hash Table)** - Decentralized peer discovery
9
- - **GossipSub** - Topic-based publish/subscribe messaging
10
- - **File Transfer** - Send and receive files and directories
11
- - **mDNS Discovery** - Local network peer discovery
12
- - **NAT Traversal** - STUN/ICE support for connecting through firewalls
13
- - **Encryption** - End-to-end encryption using Noise protocol
14
- - **Message Exchange** - String, binary, and JSON message types
15
- - **Configuration Persistence** - Save and restore client settings
16
-
17
- ## Installation
18
-
19
- ### Quick Install
20
-
21
- Install directly from npm:
22
-
23
- ```bash
24
- npm install librats
25
- ```
26
-
27
- The installation process will automatically:
28
- 1. Download all necessary source files
29
- 2. Build the native librats library using CMake
30
- 3. Build the Node.js native addon
31
- 4. Set up the bindings
32
-
33
- **No additional build steps required!**
34
-
35
- ### Prerequisites
36
-
37
- The following build tools are required and will be used automatically during installation:
38
-
39
- - **Node.js**: 20.0.0 or higher
40
- - **CMake**: Version 3.10 or higher ([download here](https://cmake.org/download/))
41
- - **C++ Compiler and Build Tools**:
42
- - **Windows**: Visual Studio Build Tools 2017 or later ([download here](https://visualstudio.microsoft.com/downloads/))
43
- - **Linux**: `build-essential` and `cmake` packages
44
- ```bash
45
- sudo apt install build-essential cmake
46
- ```
47
- - **macOS**: Xcode Command Line Tools
48
- ```bash
49
- xcode-select --install
50
- ```
51
-
52
- ### Verifying Installation
53
-
54
- After installation, you can verify everything is working:
55
-
56
- ```bash
57
- npm run verify
58
- ```
59
-
60
- This will check that the native addon is built correctly and all features are available.
61
-
62
- ### Building from Source
63
-
64
- If you're developing or need to rebuild:
65
-
66
- ```bash
67
- # Clone the repository
68
- git clone https://github.com/librats/librats.git
69
- cd librats/nodejs
70
-
71
- # Install (builds everything automatically)
72
- npm install
73
-
74
- # Verify the installation
75
- npm run verify
76
-
77
- # Or build manually
78
- npm run build
79
- ```
80
-
81
- ## Quick Start
82
-
83
- ### Basic Example
84
-
85
- ```javascript
86
- const { RatsClient, ConnectionStrategy } = require('librats');
87
-
88
- // Create a client listening on port 8080
89
- const client = new RatsClient(8080);
90
-
91
- // Set up event handlers
92
- client.onConnection((peerId) => {
93
- console.log(`Peer connected: ${peerId}`);
94
- client.sendString(peerId, 'Hello from Node.js!');
95
- });
96
-
97
- client.onString((peerId, message) => {
98
- console.log(`Received: ${message} from ${peerId}`);
99
- });
100
-
101
- // Start the client
102
- client.start();
103
-
104
- // Connect to another peer
105
- client.connect('127.0.0.1', 8081);
106
- ```
107
-
108
- ### File Transfer Example
109
-
110
- ```javascript
111
- const { RatsClient } = require('librats');
112
-
113
- const client = new RatsClient(8080);
114
-
115
- // Set up file transfer progress monitoring
116
- client.onFileProgress((transferId, progressPercent, status) => {
117
- console.log(`Transfer ${transferId}: ${progressPercent}% - ${status}`);
118
- });
119
-
120
- client.start();
121
-
122
- // Send a file to a peer
123
- const transferId = client.sendFile('peer_id_here', './myfile.txt', 'remote_file.txt');
124
- console.log(`File transfer started: ${transferId}`);
125
- ```
126
-
127
- ### GossipSub Chat Example
128
-
129
- ```javascript
130
- const { RatsClient } = require('librats');
131
-
132
- const client = new RatsClient(8080);
133
- client.start();
134
-
135
- // Subscribe to a topic
136
- client.subscribeToTopic('general-chat');
137
-
138
- // Publish a message
139
- const message = {
140
- type: 'chat',
141
- username: 'Alice',
142
- message: 'Hello everyone!',
143
- timestamp: Date.now()
144
- };
145
-
146
- client.publishJsonToTopic('general-chat', JSON.stringify(message));
147
- ```
148
-
149
- ## API Reference
150
-
151
- ### RatsClient
152
-
153
- #### Constructor
154
-
155
- - `new RatsClient(listenPort: number)` - Create a new client instance
156
-
157
- #### Basic Operations
158
-
159
- - `start(): boolean` - Start the client
160
- - `stop(): void` - Stop the client
161
- - `connect(host: string, port: number): boolean` - Connect to a peer
162
- - `connectWithStrategy(host: string, port: number, strategy: number): boolean` - Connect with specific strategy
163
- - `disconnect(peerId: string): void` - Disconnect from a peer
164
-
165
- #### Messaging
166
-
167
- - `sendString(peerId: string, message: string): boolean` - Send string message
168
- - `sendBinary(peerId: string, data: Buffer): boolean` - Send binary data
169
- - `sendJson(peerId: string, jsonStr: string): boolean` - Send JSON data
170
- - `broadcastString(message: string): number` - Broadcast string to all peers
171
- - `broadcastBinary(data: Buffer): number` - Broadcast binary to all peers
172
- - `broadcastJson(jsonStr: string): number` - Broadcast JSON to all peers
173
-
174
- #### Information
175
-
176
- - `getPeerCount(): number` - Get number of connected peers
177
- - `getOurPeerId(): string | null` - Get our peer ID
178
- - `getPeerIds(): string[]` - Get list of connected peer IDs
179
- - `getConnectionStatistics(): string | null` - Get connection statistics as JSON
180
-
181
- #### File Transfer
182
-
183
- - `sendFile(peerId: string, filePath: string, remoteFilename?: string): string | null` - Send file
184
- - `sendDirectory(peerId: string, dirPath: string, remoteDirName?: string, recursive?: boolean): string | null` - Send directory
185
- - `requestFile(peerId: string, remoteFilePath: string, localPath: string): string | null` - Request file
186
- - `requestDirectory(peerId: string, remoteDirPath: string, localDirPath: string, recursive?: boolean): string | null` - Request directory
187
- - `acceptFileTransfer(transferId: string, localPath: string): boolean` - Accept file transfer
188
- - `rejectFileTransfer(transferId: string, reason?: string): boolean` - Reject file transfer
189
- - `cancelFileTransfer(transferId: string): boolean` - Cancel file transfer
190
- - `pauseFileTransfer(transferId: string): boolean` - Pause file transfer
191
- - `resumeFileTransfer(transferId: string): boolean` - Resume file transfer
192
-
193
- #### GossipSub
194
-
195
- - `isGossipsubAvailable(): boolean` - Check if GossipSub is available
196
- - `subscribeToTopic(topic: string): boolean` - Subscribe to topic
197
- - `unsubscribeFromTopic(topic: string): boolean` - Unsubscribe from topic
198
- - `publishToTopic(topic: string, message: string): boolean` - Publish message
199
- - `publishJsonToTopic(topic: string, jsonStr: string): boolean` - Publish JSON
200
- - `getSubscribedTopics(): string[]` - Get subscribed topics
201
- - `getTopicPeers(topic: string): string[]` - Get peers in topic
202
-
203
- #### DHT
204
-
205
- - `startDhtDiscovery(dhtPort: number): boolean` - Start DHT discovery
206
- - `stopDhtDiscovery(): void` - Stop DHT discovery
207
- - `isDhtRunning(): boolean` - Check if DHT is running
208
- - `announceForHash(contentHash: string, port: number): boolean` - Announce for hash
209
-
210
- #### Encryption
211
-
212
- - `setEncryptionEnabled(enabled: boolean): boolean` - Enable/disable encryption
213
- - `isEncryptionEnabled(): boolean` - Check if encryption is enabled
214
- - `generateEncryptionKey(): string | null` - Generate new encryption key
215
- - `setEncryptionKey(keyHex: string): boolean` - Set encryption key
216
- - `getEncryptionKey(): string | null` - Get current encryption key
217
-
218
- #### Event Handlers
219
-
220
- - `onConnection(callback: (peerId: string) => void): void` - Set connection callback
221
- - `onString(callback: (peerId: string, message: string) => void): void` - Set string message callback
222
- - `onBinary(callback: (peerId: string, data: Buffer) => void): void` - Set binary message callback
223
- - `onJson(callback: (peerId: string, jsonStr: string) => void): void` - Set JSON message callback
224
- - `onDisconnect(callback: (peerId: string) => void): void` - Set disconnect callback
225
- - `onFileProgress(callback: (transferId: string, progressPercent: number, status: string) => void): void` - Set file progress callback
226
-
227
- ### Utility Functions
228
-
229
- - `getVersionString(): string` - Get librats version string
230
- - `getVersion(): VersionInfo` - Get version components
231
- - `getGitDescribe(): string` - Get git describe string
232
- - `getAbi(): number` - Get ABI version
233
-
234
- ### Constants
235
-
236
- #### ConnectionStrategy
237
-
238
- - `ConnectionStrategy.DIRECT_ONLY` - Direct connection only
239
- - `ConnectionStrategy.STUN_ASSISTED` - STUN-assisted connection
240
- - `ConnectionStrategy.ICE_FULL` - Full ICE negotiation
241
- - `ConnectionStrategy.TURN_RELAY` - TURN relay connection
242
- - `ConnectionStrategy.AUTO_ADAPTIVE` - Automatic strategy selection
243
-
244
- #### ErrorCodes
245
-
246
- - `ErrorCodes.SUCCESS` - Operation successful
247
- - `ErrorCodes.INVALID_HANDLE` - Invalid client handle
248
- - `ErrorCodes.INVALID_PARAMETER` - Invalid parameter
249
- - `ErrorCodes.NOT_RUNNING` - Client not running
250
- - `ErrorCodes.OPERATION_FAILED` - Operation failed
251
- - `ErrorCodes.PEER_NOT_FOUND` - Peer not found
252
- - `ErrorCodes.MEMORY_ALLOCATION` - Memory allocation error
253
- - `ErrorCodes.JSON_PARSE` - JSON parsing error
254
-
255
- ## Examples
256
-
257
- The `examples/` directory contains comprehensive examples:
258
-
259
- - **`basic_client.js`** - Basic peer-to-peer networking and messaging
260
- - **`file_transfer.js`** - File and directory transfer with interactive CLI
261
- - **`gossipsub_chat.js`** - Topic-based chat using GossipSub
262
-
263
- ### Running Examples
264
-
265
- ```bash
266
- # Basic client (listens on port 8080)
267
- node examples/basic_client.js
268
-
269
- # Basic client connecting to another peer
270
- node examples/basic_client.js 8081 127.0.0.1 8080
271
-
272
- # File transfer client
273
- node examples/file_transfer.js 8080
274
-
275
- # GossipSub chat
276
- node examples/gossipsub_chat.js 8080 Alice
277
- ```
278
-
279
- ## Testing
280
-
281
- Run the test suite:
282
-
283
- ```bash
284
- npm test
285
- ```
286
-
287
- Or run the simple test script:
288
-
289
- ```bash
290
- node test/test.js
291
- ```
292
-
293
- ## Building from Source
294
-
295
- ### Debug Build
296
-
297
- ```bash
298
- npm run build
299
- ```
300
-
301
- ### Clean Build
302
-
303
- ```bash
304
- npm run clean
305
- npm run build
306
- ```
307
-
308
- ## TypeScript Support
309
-
310
- Full TypeScript definitions are included. Import types:
311
-
312
- ```typescript
313
- import { RatsClient, ConnectionStrategy, ErrorCodes, VersionInfo } from 'librats';
314
-
315
- const client: RatsClient = new RatsClient(8080);
316
- client.start();
317
- ```
318
-
319
- ## Error Handling
320
-
321
- Most operations return boolean values indicating success/failure. For detailed error information, check the console output or use the statistics functions:
322
-
323
- ```javascript
324
- const stats = client.getConnectionStatistics();
325
- if (stats) {
326
- const parsed = JSON.parse(stats);
327
- console.log('Connection stats:', parsed);
328
- }
329
- ```
330
-
331
- ## Performance Considerations
332
-
333
- - Use binary messages for large data transfers
334
- - Enable encryption only when needed (adds overhead)
335
- - Monitor file transfer progress for large files
336
- - Use appropriate connection strategies for your network environment
337
-
338
- ## Platform Support
339
-
340
- - **Windows** - Requires Visual Studio Build Tools
341
- - **Linux** - Requires build-essential
342
- - **macOS** - Requires Xcode Command Line Tools
343
- - **Android** - Supported via native Android bindings (separate package)
344
-
345
- ## Contributing
346
-
347
- 1. Fork the repository
348
- 2. Create a feature branch
349
- 3. Make your changes
350
- 4. Add tests for new functionality
351
- 5. Submit a pull request
352
-
353
- ## License
354
-
355
- This project is licensed under the MIT License - see the LICENSE file for details.
356
-
357
- ## Troubleshooting
358
-
359
- ### Build Issues
360
-
361
- **Windows**: Ensure Visual Studio Build Tools are installed
362
- ```bash
363
- npm install --global windows-build-tools
364
- ```
365
-
366
- **Linux**: Install build dependencies
367
- ```bash
368
- sudo apt install build-essential python3
369
- ```
370
-
371
- **macOS**: Install Xcode Command Line Tools
372
- ```bash
373
- xcode-select --install
374
- ```
375
-
376
- ### Runtime Issues
377
-
378
- **Port already in use**: Choose a different port or kill the process using the port
379
- ```bash
380
- # Find process using port
381
- netstat -tulpn | grep :8080
382
-
383
- # Kill process
384
- kill -9 <pid>
385
- ```
386
-
387
- **Permission denied**: Run with appropriate permissions or use ports > 1024
388
-
389
- **Connection timeout**: Check firewall settings and ensure peers are reachable
390
-
391
- ### Debug Mode
392
-
393
- Enable debug logging by setting environment variable:
394
- ```bash
395
- export LIBRATS_DEBUG=1
396
- node examples/basic_client.js
397
- ```
398
-
399
- ## Support
400
-
401
- - [GitHub Issues](https://github.com/librats/librats/issues)
402
- - [Documentation](https://librats.github.io/)
403
- - [Examples Repository](https://github.com/librats/librats/tree/main/nodejs/examples)
404
-
405
- For more advanced usage, see the [C API documentation](../docs/) and the [main project README](../README.md).
1
+ # LibRats Node.js Bindings
2
+
3
+ Node.js bindings for librats - A high-performance peer-to-peer networking library with support for DHT, GossipSub, file transfer, NAT traversal, and more.
4
+
5
+ ## Features
6
+
7
+ - **Peer-to-peer networking** - Direct connections between peers
8
+ - **DHT (Distributed Hash Table)** - Decentralized peer discovery
9
+ - **GossipSub** - Topic-based publish/subscribe messaging
10
+ - **File Transfer** - Send and receive files and directories
11
+ - **mDNS Discovery** - Local network peer discovery
12
+ - **NAT Traversal** - STUN/ICE support for connecting through firewalls
13
+ - **Encryption** - End-to-end encryption using Noise protocol
14
+ - **Message Exchange** - String, binary, and JSON message types
15
+ - **Configuration Persistence** - Save and restore client settings
16
+
17
+ ## Installation
18
+
19
+ ### Quick Install
20
+
21
+ Install directly from npm:
22
+
23
+ ```bash
24
+ npm install librats
25
+ ```
26
+
27
+ The installation process will automatically:
28
+ 1. Download all necessary source files
29
+ 2. Build the native librats library using CMake
30
+ 3. Build the Node.js native addon
31
+ 4. Set up the bindings
32
+
33
+ **No additional build steps required!**
34
+
35
+ ### Prerequisites
36
+
37
+ The following build tools are required and will be used automatically during installation:
38
+
39
+ - **Node.js**: 20.0.0 or higher
40
+ - **CMake**: Version 3.10 or higher ([download here](https://cmake.org/download/))
41
+ - **C++ Compiler and Build Tools**:
42
+ - **Windows**: Visual Studio Build Tools 2017 or later ([download here](https://visualstudio.microsoft.com/downloads/))
43
+ - **Linux**: `build-essential` and `cmake` packages
44
+ ```bash
45
+ sudo apt install build-essential cmake
46
+ ```
47
+ - **macOS**: Xcode Command Line Tools
48
+ ```bash
49
+ xcode-select --install
50
+ ```
51
+
52
+ ### Verifying Installation
53
+
54
+ After installation, you can verify everything is working:
55
+
56
+ ```bash
57
+ npm run verify
58
+ ```
59
+
60
+ This will check that the native addon is built correctly and all features are available.
61
+
62
+ ### Building from Source
63
+
64
+ If you're developing or need to rebuild:
65
+
66
+ ```bash
67
+ # Clone the repository
68
+ git clone https://github.com/librats/librats.git
69
+ cd librats/nodejs
70
+
71
+ # Install (builds everything automatically)
72
+ npm install
73
+
74
+ # Verify the installation
75
+ npm run verify
76
+
77
+ # Or build manually
78
+ npm run build
79
+ ```
80
+
81
+ ## Quick Start
82
+
83
+ ### Basic Example
84
+
85
+ ```javascript
86
+ const { RatsClient, ConnectionStrategy } = require('librats');
87
+
88
+ // Create a client listening on port 8080
89
+ const client = new RatsClient(8080);
90
+
91
+ // Set up event handlers
92
+ client.onConnection((peerId) => {
93
+ console.log(`Peer connected: ${peerId}`);
94
+ client.sendString(peerId, 'Hello from Node.js!');
95
+ });
96
+
97
+ client.onString((peerId, message) => {
98
+ console.log(`Received: ${message} from ${peerId}`);
99
+ });
100
+
101
+ // Start the client
102
+ client.start();
103
+
104
+ // Connect to another peer
105
+ client.connect('127.0.0.1', 8081);
106
+ ```
107
+
108
+ ### File Transfer Example
109
+
110
+ ```javascript
111
+ const { RatsClient } = require('librats');
112
+
113
+ const client = new RatsClient(8080);
114
+
115
+ // Set up file transfer progress monitoring
116
+ client.onFileProgress((transferId, progressPercent, status) => {
117
+ console.log(`Transfer ${transferId}: ${progressPercent}% - ${status}`);
118
+ });
119
+
120
+ client.start();
121
+
122
+ // Send a file to a peer
123
+ const transferId = client.sendFile('peer_id_here', './myfile.txt', 'remote_file.txt');
124
+ console.log(`File transfer started: ${transferId}`);
125
+ ```
126
+
127
+ ### GossipSub Chat Example
128
+
129
+ ```javascript
130
+ const { RatsClient } = require('librats');
131
+
132
+ const client = new RatsClient(8080);
133
+ client.start();
134
+
135
+ // Subscribe to a topic
136
+ client.subscribeToTopic('general-chat');
137
+
138
+ // Publish a message
139
+ const message = {
140
+ type: 'chat',
141
+ username: 'Alice',
142
+ message: 'Hello everyone!',
143
+ timestamp: Date.now()
144
+ };
145
+
146
+ client.publishJsonToTopic('general-chat', JSON.stringify(message));
147
+ ```
148
+
149
+ ## API Reference
150
+
151
+ ### RatsClient
152
+
153
+ #### Constructor
154
+
155
+ - `new RatsClient(listenPort: number)` - Create a new client instance
156
+
157
+ #### Basic Operations
158
+
159
+ - `start(): boolean` - Start the client
160
+ - `stop(): void` - Stop the client
161
+ - `connect(host: string, port: number): boolean` - Connect to a peer
162
+ - `connectWithStrategy(host: string, port: number, strategy: number): boolean` - Connect with specific strategy
163
+ - `disconnect(peerId: string): void` - Disconnect from a peer
164
+
165
+ #### Messaging
166
+
167
+ - `sendString(peerId: string, message: string): boolean` - Send string message
168
+ - `sendBinary(peerId: string, data: Buffer): boolean` - Send binary data
169
+ - `sendJson(peerId: string, jsonStr: string): boolean` - Send JSON data
170
+ - `broadcastString(message: string): number` - Broadcast string to all peers
171
+ - `broadcastBinary(data: Buffer): number` - Broadcast binary to all peers
172
+ - `broadcastJson(jsonStr: string): number` - Broadcast JSON to all peers
173
+
174
+ #### Information
175
+
176
+ - `getPeerCount(): number` - Get number of connected peers
177
+ - `getOurPeerId(): string | null` - Get our peer ID
178
+ - `getPeerIds(): string[]` - Get list of connected peer IDs
179
+ - `getConnectionStatistics(): string | null` - Get connection statistics as JSON
180
+
181
+ #### File Transfer
182
+
183
+ - `sendFile(peerId: string, filePath: string, remoteFilename?: string): string | null` - Send file
184
+ - `sendDirectory(peerId: string, dirPath: string, remoteDirName?: string, recursive?: boolean): string | null` - Send directory
185
+ - `requestFile(peerId: string, remoteFilePath: string, localPath: string): string | null` - Request file
186
+ - `requestDirectory(peerId: string, remoteDirPath: string, localDirPath: string, recursive?: boolean): string | null` - Request directory
187
+ - `acceptFileTransfer(transferId: string, localPath: string): boolean` - Accept file transfer
188
+ - `rejectFileTransfer(transferId: string, reason?: string): boolean` - Reject file transfer
189
+ - `cancelFileTransfer(transferId: string): boolean` - Cancel file transfer
190
+ - `pauseFileTransfer(transferId: string): boolean` - Pause file transfer
191
+ - `resumeFileTransfer(transferId: string): boolean` - Resume file transfer
192
+
193
+ #### GossipSub
194
+
195
+ - `isGossipsubAvailable(): boolean` - Check if GossipSub is available
196
+ - `subscribeToTopic(topic: string): boolean` - Subscribe to topic
197
+ - `unsubscribeFromTopic(topic: string): boolean` - Unsubscribe from topic
198
+ - `publishToTopic(topic: string, message: string): boolean` - Publish message
199
+ - `publishJsonToTopic(topic: string, jsonStr: string): boolean` - Publish JSON
200
+ - `getSubscribedTopics(): string[]` - Get subscribed topics
201
+ - `getTopicPeers(topic: string): string[]` - Get peers in topic
202
+
203
+ #### DHT
204
+
205
+ - `startDhtDiscovery(dhtPort: number): boolean` - Start DHT discovery
206
+ - `stopDhtDiscovery(): void` - Stop DHT discovery
207
+ - `isDhtRunning(): boolean` - Check if DHT is running
208
+ - `announceForHash(contentHash: string, port: number): boolean` - Announce for hash
209
+
210
+ #### Encryption
211
+
212
+ - `setEncryptionEnabled(enabled: boolean): boolean` - Enable/disable encryption
213
+ - `isEncryptionEnabled(): boolean` - Check if encryption is enabled
214
+ - `generateEncryptionKey(): string | null` - Generate new encryption key
215
+ - `setEncryptionKey(keyHex: string): boolean` - Set encryption key
216
+ - `getEncryptionKey(): string | null` - Get current encryption key
217
+
218
+ #### Event Handlers
219
+
220
+ - `onConnection(callback: (peerId: string) => void): void` - Set connection callback
221
+ - `onString(callback: (peerId: string, message: string) => void): void` - Set string message callback
222
+ - `onBinary(callback: (peerId: string, data: Buffer) => void): void` - Set binary message callback
223
+ - `onJson(callback: (peerId: string, jsonStr: string) => void): void` - Set JSON message callback
224
+ - `onDisconnect(callback: (peerId: string) => void): void` - Set disconnect callback
225
+ - `onFileProgress(callback: (transferId: string, progressPercent: number, status: string) => void): void` - Set file progress callback
226
+
227
+ ### Utility Functions
228
+
229
+ - `getVersionString(): string` - Get librats version string
230
+ - `getVersion(): VersionInfo` - Get version components
231
+ - `getGitDescribe(): string` - Get git describe string
232
+ - `getAbi(): number` - Get ABI version
233
+
234
+ ### Constants
235
+
236
+ #### ConnectionStrategy
237
+
238
+ - `ConnectionStrategy.DIRECT_ONLY` - Direct connection only
239
+ - `ConnectionStrategy.STUN_ASSISTED` - STUN-assisted connection
240
+ - `ConnectionStrategy.ICE_FULL` - Full ICE negotiation
241
+ - `ConnectionStrategy.TURN_RELAY` - TURN relay connection
242
+ - `ConnectionStrategy.AUTO_ADAPTIVE` - Automatic strategy selection
243
+
244
+ #### ErrorCodes
245
+
246
+ - `ErrorCodes.SUCCESS` - Operation successful
247
+ - `ErrorCodes.INVALID_HANDLE` - Invalid client handle
248
+ - `ErrorCodes.INVALID_PARAMETER` - Invalid parameter
249
+ - `ErrorCodes.NOT_RUNNING` - Client not running
250
+ - `ErrorCodes.OPERATION_FAILED` - Operation failed
251
+ - `ErrorCodes.PEER_NOT_FOUND` - Peer not found
252
+ - `ErrorCodes.MEMORY_ALLOCATION` - Memory allocation error
253
+ - `ErrorCodes.JSON_PARSE` - JSON parsing error
254
+
255
+ ## Examples
256
+
257
+ The `examples/` directory contains comprehensive examples:
258
+
259
+ - **`basic_client.js`** - Basic peer-to-peer networking and messaging
260
+ - **`file_transfer.js`** - File and directory transfer with interactive CLI
261
+ - **`gossipsub_chat.js`** - Topic-based chat using GossipSub
262
+
263
+ ### Running Examples
264
+
265
+ ```bash
266
+ # Basic client (listens on port 8080)
267
+ node examples/basic_client.js
268
+
269
+ # Basic client connecting to another peer
270
+ node examples/basic_client.js 8081 127.0.0.1 8080
271
+
272
+ # File transfer client
273
+ node examples/file_transfer.js 8080
274
+
275
+ # GossipSub chat
276
+ node examples/gossipsub_chat.js 8080 Alice
277
+ ```
278
+
279
+ ## Testing
280
+
281
+ Run the test suite:
282
+
283
+ ```bash
284
+ npm test
285
+ ```
286
+
287
+ Or run the simple test script:
288
+
289
+ ```bash
290
+ node test/test.js
291
+ ```
292
+
293
+ ## Building from Source
294
+
295
+ ### Debug Build
296
+
297
+ ```bash
298
+ npm run build
299
+ ```
300
+
301
+ ### Clean Build
302
+
303
+ ```bash
304
+ npm run clean
305
+ npm run build
306
+ ```
307
+
308
+ ## TypeScript Support
309
+
310
+ Full TypeScript definitions are included. Import types:
311
+
312
+ ```typescript
313
+ import { RatsClient, ConnectionStrategy, ErrorCodes, VersionInfo } from 'librats';
314
+
315
+ const client: RatsClient = new RatsClient(8080);
316
+ client.start();
317
+ ```
318
+
319
+ ## Error Handling
320
+
321
+ Most operations return boolean values indicating success/failure. For detailed error information, check the console output or use the statistics functions:
322
+
323
+ ```javascript
324
+ const stats = client.getConnectionStatistics();
325
+ if (stats) {
326
+ const parsed = JSON.parse(stats);
327
+ console.log('Connection stats:', parsed);
328
+ }
329
+ ```
330
+
331
+ ## Performance Considerations
332
+
333
+ - Use binary messages for large data transfers
334
+ - Enable encryption only when needed (adds overhead)
335
+ - Monitor file transfer progress for large files
336
+ - Use appropriate connection strategies for your network environment
337
+
338
+ ## Platform Support
339
+
340
+ - **Windows** - Requires Visual Studio Build Tools
341
+ - **Linux** - Requires build-essential
342
+ - **macOS** - Requires Xcode Command Line Tools
343
+ - **Android** - Supported via native Android bindings (separate package)
344
+
345
+ ## Contributing
346
+
347
+ 1. Fork the repository
348
+ 2. Create a feature branch
349
+ 3. Make your changes
350
+ 4. Add tests for new functionality
351
+ 5. Submit a pull request
352
+
353
+ ## License
354
+
355
+ This project is licensed under the MIT License - see the LICENSE file for details.
356
+
357
+ ## Troubleshooting
358
+
359
+ ### Build Issues
360
+
361
+ **Windows**: Ensure Visual Studio Build Tools are installed
362
+ ```bash
363
+ npm install --global windows-build-tools
364
+ ```
365
+
366
+ **Linux**: Install build dependencies
367
+ ```bash
368
+ sudo apt install build-essential python3
369
+ ```
370
+
371
+ **macOS**: Install Xcode Command Line Tools
372
+ ```bash
373
+ xcode-select --install
374
+ ```
375
+
376
+ ### Runtime Issues
377
+
378
+ **Port already in use**: Choose a different port or kill the process using the port
379
+ ```bash
380
+ # Find process using port
381
+ netstat -tulpn | grep :8080
382
+
383
+ # Kill process
384
+ kill -9 <pid>
385
+ ```
386
+
387
+ **Permission denied**: Run with appropriate permissions or use ports > 1024
388
+
389
+ **Connection timeout**: Check firewall settings and ensure peers are reachable
390
+
391
+ ### Debug Mode
392
+
393
+ Enable debug logging by setting environment variable:
394
+ ```bash
395
+ export LIBRATS_DEBUG=1
396
+ node examples/basic_client.js
397
+ ```
398
+
399
+ ## Support
400
+
401
+ - [GitHub Issues](https://github.com/librats/librats/issues)
402
+ - [Documentation](https://librats.github.io/)
403
+ - [Examples Repository](https://github.com/librats/librats/tree/main/nodejs/examples)
404
+
405
+ For more advanced usage, see the [C API documentation](../docs/) and the [main project README](../README.md).