Support nodeUrls in string array format (host:port) for simpler multi-node configuration
A Node.js client for Apache IoTDB with support for SessionPool and TableSessionPool, providing efficient connection management and comprehensive query capabilities.
npm install iotdb-client-nodejs
import { Session } from 'iotdb-client-nodejs'; const session = new Session({ host: 'localhost', port: 6667, username: 'root', password: 'root', }); await session.open(); // Execute non-query statement await session.executeNonQueryStatement('CREATE DATABASE root.test'); // Execute query statement with default timeout (60 seconds) const result = await session.executeQueryStatement('SHOW DATABASES'); console.log('Columns:', result.columns); console.log('Rows:', result.rows); // Execute query with custom timeout (30 seconds) const customResult = await session.executeQueryStatement('SELECT * FROM root.test.**', 30000); // Insert tablet data await session.insertTablet({ deviceId: 'root.test.device1', measurements: ['temperature', 'humidity'], dataTypes: [3, 3], // FLOAT timestamps: [Date.now(), Date.now() + 1000], values: [ [25.5, 60.0], [26.0, 61.5], ], }); await session.close();
The Builder pattern provides a more elegant and fluent API for configuration:
import { Session, ConfigBuilder } from 'iotdb-client-nodejs'; // Build a session configuration const session = new Session( new ConfigBuilder() .host('localhost') .port(6667) .username('root') .password('root') .fetchSize(1024) .timezone('UTC+8') .build() ); await session.open(); // ... use session await session.close();
import { SessionPool } from 'iotdb-client-nodejs'; const pool = new SessionPool('localhost', 6667, { username: 'root', password: 'root', maxPoolSize: 10, minPoolSize: 2, maxIdleTime: 60000, waitTimeout: 60000, }); await pool.init(); // Execute queries using the pool const result = await pool.executeQueryStatement('SELECT * FROM root.test.**'); // Execute non-query statements await pool.executeNonQueryStatement( 'CREATE TIMESERIES root.test.device1.temperature WITH DATATYPE=FLOAT' ); // Insert data await pool.insertTablet({ deviceId: 'root.test.device1', measurements: ['temperature'], dataTypes: [3], // FLOAT timestamps: [Date.now()], values: [[25.5]], }); // Get pool statistics console.log('Pool size:', pool.getPoolSize()); console.log('Available:', pool.getAvailableSize()); await pool.close();
For more control, you can explicitly get and release sessions from the pool:
import { SessionPool } from 'iotdb-client-nodejs'; const pool = new SessionPool('localhost', 6667, { username: 'root', password: 'root', maxPoolSize: 10, }); await pool.init(); // Get a session from the pool const session = await pool.getSession(); try { // Use the session for multiple operations await session.executeNonQueryStatement('CREATE DATABASE root.test'); const result = await session.executeQueryStatement('SHOW DATABASES'); await session.insertTablet({ deviceId: 'root.test.device1', measurements: ['temperature'], dataTypes: [3], timestamps: [Date.now()], values: [[25.5]], }); } finally { // Always release the session back to the pool pool.releaseSession(session); } await pool.close();
When nodes have different host:port combinations, use the nodeUrls configuration with string array format:
import { SessionPool, PoolConfigBuilder } from 'iotdb-client-nodejs'; // Using config object with string array (RECOMMENDED) const pool1 = new SessionPool({ nodeUrls: [ 'node1.example.com:6667', 'node2.example.com:6668', 'node3.example.com:6669', ], username: 'root', password: 'root', maxPoolSize: 15, minPoolSize: 3, }); // Or using Builder pattern with string array const pool2 = new SessionPool( new PoolConfigBuilder() .nodeUrls([ 'node1.example.com:6667', 'node2.example.com:6668', 'node3.example.com:6669', ]) .username('root') .password('root') .maxPoolSize(15) .minPoolSize(3) .build() ); await pool1.init(); // Connections will be distributed across all nodes using round-robin
You can also use the object format for nodeUrls:
const pool = new SessionPool({ nodeUrls: [ { host: 'node1.example.com', port: 6667 }, { host: 'node2.example.com', port: 6668 }, { host: 'node3.example.com', port: 6669 }, ], username: 'root', password: 'root', maxPoolSize: 15, });
When all nodes share the same port:
import { SessionPool } from 'iotdb-client-nodejs'; const pool = new SessionPool( ['node1.example.com', 'node2.example.com', 'node3.example.com'], 6667, { username: 'root', password: 'root', maxPoolSize: 15, } ); await pool.init(); // Connections will be distributed across all nodes using round-robin
import { Session } from 'iotdb-client-nodejs'; import * as fs from 'fs'; const session = new Session({ host: 'localhost', port: 6667, username: 'root', password: 'root', enableSSL: true, sslOptions: { ca: fs.readFileSync('/path/to/ca.crt'), cert: fs.readFileSync('/path/to/client.crt'), key: fs.readFileSync('/path/to/client.key'), rejectUnauthorized: true, }, }); await session.open();
import { TableSessionPool } from 'iotdb-client-nodejs'; const tablePool = new TableSessionPool('localhost', 6667, { username: 'root', password: 'root', database: 'my_database', // Set default database for table model maxPoolSize: 10, minPoolSize: 2, }); await tablePool.init(); // Execute queries in table mode const result = await tablePool.executeQueryStatement('SHOW DATABASES'); await tablePool.close();
Fluent API for building Session configurations:
import { ConfigBuilder } from 'iotdb-client-nodejs'; const config = new ConfigBuilder() .host('localhost') .port(6667) .username('root') .password('root') .database('mydb') .timezone('UTC+8') .fetchSize(2048) .enableSSL(false) .build();
Methods:
host(host: string): this - Set the hostport(port: number): this - Set the portnodeUrls(nodeUrls: EndPoint[]): this - Set multiple node URLsusername(username: string): this - Set the usernamepassword(password: string): this - Set the passworddatabase(database: string): this - Set the databasetimezone(timezone: string): this - Set the timezonefetchSize(fetchSize: number): this - Set the fetch sizeenableSSL(enable: boolean): this - Enable or disable SSLsslOptions(sslOptions: SSLOptions): this - Set SSL optionsbuild(): Config - Build and return the configurationFluent API for building SessionPool configurations (extends ConfigBuilder):
import { PoolConfigBuilder } from 'iotdb-client-nodejs'; const config = new PoolConfigBuilder() .host('localhost') .port(6667) .username('root') .password('root') .maxPoolSize(20) .minPoolSize(5) .maxIdleTime(30000) .waitTimeout(45000) .build();
Additional Methods:
maxPoolSize(size: number): this - Set maximum pool sizeminPoolSize(size: number): this - Set minimum pool sizemaxIdleTime(time: number): this - Set maximum idle time (ms)waitTimeout(timeout: number): this - Set wait timeout (ms)build(): PoolConfig - Build and return the pool configurationIoTDB Node.js client supports all IoTDB data types including BOOLEAN, INT32, INT64, FLOAT, DOUBLE, TEXT, BLOB, STRING, DATE, and TIMESTAMP. See DATA_TYPES.md for comprehensive documentation on:
Option 1: Using config object
new Session(config: Config)
Option 2: Using Builder pattern (Recommended)
new Session(new ConfigBuilder()...build())
The config must include either:
host and port for single node connectionnodeUrls for multi-node connection (uses first node)async open(): Promise<void> - Open the sessionasync close(): Promise<void> - Close the sessionasync executeQueryStatement(sql: string, timeoutMs?: number): Promise<QueryResult> - Execute a query with optional timeout (default: 60000ms)async executeNonQueryStatement(sql: string): Promise<void> - Execute a non-query statementasync insertTablet(tablet: Tablet): Promise<void> - Insert tablet dataisOpen(): boolean - Check if session is openOption 1: Traditional API (Backward compatible)
new SessionPool(hosts: string | string[], port: number, config?: Partial<PoolConfig>)
Option 2: Using config object with nodeUrls
new SessionPool(config: PoolConfig)
Option 3: Using Builder pattern (Recommended)
new SessionPool(new PoolConfigBuilder()...build())
Connection Management:
async init(): Promise<void> - Initialize the poolasync close(): Promise<void> - Close all connectionsAutomatic Session Management:
async executeQueryStatement(sql: string, timeoutMs?: number): Promise<QueryResult> - Execute a query with optional timeout (default: 60000ms)async executeNonQueryStatement(sql: string): Promise<void> - Execute a non-query statementasync insertTablet(tablet: Tablet): Promise<void> - Insert tablet dataExplicit Session Management:
async getSession(): Promise<Session> - Get a session from the pool (must be released)releaseSession(session: Session): void - Release a session back to the poolPool Statistics:
getPoolSize(): number - Get current pool sizegetAvailableSize(): number - Get available connectionsgetInUseSize(): number - Get number of sessions currently in useSame as SessionPool but optimized for table model operations. Automatically executes USE DATABASE when configured with a database. All query methods support the same timeout parameter (default: 60000ms).
Same constructor options as SessionPool.
interface Config { host?: string; port?: number; nodeUrls?: string[] | EndPoint[]; // String array format: ["host1:6667", "host2:6668"] username?: string; password?: string; database?: string; timezone?: string; fetchSize?: number; enableSSL?: boolean; sslOptions?: SSLOptions; }
Note: Either host/port OR nodeUrls must be provided.
nodeUrls in string array format (e.g., ["host1:6667", "host2:6668"]) for nodes with different ports (RECOMMENDED)[{ host, port }] is also supported for backward compatibilityinterface EndPoint { host: string; port: number; }
interface PoolConfig extends Config { maxPoolSize?: number; minPoolSize?: number; maxIdleTime?: number; waitTimeout?: number; }
interface Tablet { deviceId: string; measurements: string[]; dataTypes: number[]; // 0=BOOLEAN, 1=INT32, 2=INT64, 3=FLOAT, 4=DOUBLE, 5=TEXT timestamps: number[]; values: any[][]; }
interface QueryResult { columns: string[]; dataTypes: string[]; rows: any[][]; queryId?: number; }
When using insertTablet, specify data types using these constants:
0 - BOOLEAN1 - INT322 - INT643 - FLOAT4 - DOUBLE5 - TEXTThe new version maintains full backward compatibility while adding new features. No changes are required for existing code, but you may want to adopt the new features:
Old way (still works, but limited to same port):
const pool = new SessionPool( ['node1', 'node2', 'node3'], 6667, { username: 'root', password: 'root' } );
New way (supports different ports per node with string format - RECOMMENDED):
const pool = new SessionPool({ nodeUrls: [ 'node1:6667', 'node2:6668', 'node3:6669', ], username: 'root', password: 'root', });
Alternative (object format also supported):
const pool = new SessionPool({ nodeUrls: [ { host: 'node1', port: 6667 }, { host: 'node2', port: 6668 }, { host: 'node3', port: 6669 }, ], username: 'root', password: 'root', });
Old way (still works):
const session = new Session({ host: 'localhost', port: 6667, username: 'root', password: 'root', fetchSize: 2048, });
New way (more fluent):
import { ConfigBuilder } from 'iotdb-client-nodejs'; const session = new Session( new ConfigBuilder() .host('localhost') .port(6667) .username('root') .password('root') .fetchSize(2048) .build() );
Old way (still works):
// Pool automatically manages sessions const result = await pool.executeQueryStatement('SELECT ...');
New way (more control):
// Explicitly get and release sessions const session = await pool.getSession(); try { const result1 = await session.executeQueryStatement('SELECT ...'); const result2 = await session.executeQueryStatement('SELECT ...'); // ... multiple operations with same session } finally { pool.releaseSession(session); }
npm install
npm run build
# Run all tests npm test # Run unit tests only npm run test:unit # Run E2E tests (requires IoTDB instance) export IOTDB_HOST=localhost export IOTDB_PORT=6667 npm run test:e2e
npm run lint
See the examples/ directory for more usage examples:
examples/basic-session.ts - Basic session usageexamples/session-pool.ts - SessionPool usageexamples/table-session-pool.ts - TableSessionPool usageexamples/multi-node.ts - Multi-node configurationexamples/ssl-connection.ts - SSL/TLS connectionContributions are welcome! Please feel free to submit a Pull Request.
Apache License 2.0