docs/en/14-reference/05-connector/35-node.md
import Tabs from "@theme/Tabs"; import TabItem from "@theme/TabItem"; import RequestId from "../../assets/resources/_request_id.mdx";
@tdengine/websocket is the official Node.js language connector for TDengine. Node.js developers can use it to develop applications that access the TDengine database.
The source code for the Node.js connector is hosted on GitHub.
Supports Node.js 14 and above.
Support all platforms that can run Node.js.
| Node.js Connector Version | Major Changes | TDengine Version |
|---|---|---|
| 3.2.2 | Fix timezone handling issues on Windows systems. | - |
| 3.2.1 | Fix SQL query result sorting issue. | - |
| 3.2.0 | Optimize STMT parameter binding to improve write efficiency. | - |
| 3.1.9 | Fix timezone handling in WebSocket connections. | - |
| 3.1.8 | Fix when the connection pool returns unavailable connections during network anomalies. | - |
| 3.1.7 | Fix cloud service TMQ connection parameter issue. | - |
| 3.1.6 | 1. Check if the connector supports database version. |
For error code information please refer to Error Codes
The table below shows the mapping between TDengine DataType and Node.js DataType
| TDengine DataType | Node.js DataType |
|---|---|
| TIMESTAMP | bigint |
| TINYINT | number |
| SMALLINT | number |
| INT | number |
| BIGINT | bigint |
| TINYINT UNSIGNED | number |
| SMALLINT UNSIGNED | number |
| INT UNSIGNED | number |
| BIGINT UNSIGNED | bigint |
| FLOAT | number |
| DOUBLE | number |
| BOOL | boolean |
| BINARY | string |
| NCHAR | string |
| JSON | string |
| VARBINARY | ArrayBuffer |
| GEOMETRY | ArrayBuffer |
Note: JSON type is only supported in tags.
| Example Program | Description of Example Program |
|---|---|
| sql_example | Basic usage such as establishing connections, executing SQL, etc. |
| stmt_example | Example of binding parameters for insertion. |
| line_example | Line protocol writing example. |
| tmq_example | Example of using subscriptions. |
| all_type_query | Example supporting all types. |
| all_type_stmt | Example of parameter binding supporting all types. |
@tdengine/websocket) supports Node.js version 14 and above. Versions below 14 may have package compatibility issues."Unable to establish connection" or "Unable to resolve FQDN"
Reason: Generally, it is because the FQDN is not configured correctly.
Node.js connector (@tdengine/websocket), which connects to a TDengine instance through the WebSocket interface provided by taosAdapter.
[+<protocol>]://[[<username>:<password>@]<host>:<port>][/<database>][?<p1>=<v1>[&<p2>=<v2>]]
|------------|---|-----------|-----------|------|------|------------|-----------------------|
| protocol | | username | password | host | port | database | params |
protocol: Use the websocket protocol to establish a connection. For example, ws://localhost:6041
username/password: Username and password for the database.
host/port: The host_name parameter supports valid domain names or IP addresses. The @tdengine/websocket supports both IPv4 and IPv6 formats. For IPv6 addresses, square brackets must be used (e.g., [::1] or [2001:db8:1234:5678::1]) to avoid port number parsing conflicts.
database: Database name.
params: Other parameters. For example, token.
Complete DSN example:
// IPV4:
ws://root:taosdata@localhost:6041
// IPV6:
ws://root:taosdata@[::1]:6041
In addition to obtaining a connection through a specified URL, you can also use WSConfig to specify parameters when establishing a connection.
const taos = require("@tdengine/websocket");
async function createConnect() {
try {
let url = 'ws://127.0.0.1:6041'
let conf = new taos.WSConfig(url)
conf.setUser('root')
conf.setPwd('taosdata')
conf.setDb('db')
conf.setTimeOut(500)
let wsSql = await taos.sqlConnect(conf)
} catch (e) {
console.error(e);
}
}
The configurations in WSConfig are as follows:
static async open(wsConfig:WSConfig):Promise<WsSql>
wsConfig: Connection configuration, see the WSConfig section above.TDWebSocketClientError exception.destroyed()
TDWebSocketClientError exception.async version(): Promise<string>
TDWebSocketClientError exception.async exec(sql: string, reqId?: number): Promise<TaosResult>
sql: The SQL statement to be executed.reqId: Request ID, optional, used for issue tracking.TaosResult {
affectRows: number, // Number of rows affected
timing: number, // Execution duration
totalTime: number, // Total response time
}
TDWebSocketClientError exception if connection fails.async query(sql: string, reqId?:number): Promise<WSRows>
sql: The SQL query statement to be executed.reqId: Request ID, optional, used for issue tracking.TDWebSocketClientError exception if connection fails.getMeta():Array<TDengineMeta> | null
Interface Description: Get the number, type, and length of columns in the query result.
Return Value: Array of TDengineMeta data objects.
export interface TDengineMeta {
name: string,
type: string,
length: number,
}
async next(): Promise<boolean>
TDWebSocketClientError exception if connection fails.getData(): Array<any>
async close():Promise<void>
TDWebSocketClientError exception if connection fails.async schemalessInsert(lines: Array<string>, protocol: SchemalessProto, precision: Precision, ttl: number, reqId?: number): Promise<void>
lines: Array of data to be written, the specific data format for schemaless can refer to Schemaless Writing.protocol: Protocol type
SchemalessProto.InfluxDBLineProtocol: InfluxDB Line Protocol.SchemalessProto.OpenTSDBTelnetLineProtocol: OpenTSDB Text Line Protocol.SchemalessProto.OpenTSDBJsonFormatProtocol: JSON Protocol format.precision: Time precision
Precision.HOURS: HoursPrecision.MINUTES: MinutesPrecision.SECONDS: SecondsPrecision.MILLI_SECONDS: MillisecondsPrecision.MICRO_SECONDS: MicrosecondsPrecision.NANO_SECONDS: Nanosecondsttl: Table expiration time, in days.reqId: Optional, used for issue tracking.TaosResultError exception if connection fails.async stmtInit(reqId?:number): Promise<WsStmt>
reqId: Request id is optional, used for issue tracking.TDWebSocketClientError if connection fails.async prepare(sql: string): Promise<void>
sql: Precompiled SQL statement.TDWebSocketClientError if connection fails.async setTableName(tableName: string): Promise<void>
tableName: Table name, to specify a database, use: db_name.table_name.TDWebSocketClientError if connection fails.
Set binding data through StmtBindParams object.setBoolean(params :any[])
params: List of boolean types.TDWebSocketClientError if connection fails.setTinyInt(params :any[])setUTinyInt(params :any[])setSmallInt(params :any[])setUSmallInt(params :any[])setInt(params :any[])setUInt(params :any[])setBigint(params :any[])setUBigint(params :any[])setFloat(params :any[])setDouble(params :any[])setVarchar(params :any[])setBinary(params :any[])setNchar(params :any[])setJson(params :any[])setVarBinary(params :any[])setGeometry(params :any[])setTimestamp(params :any[])async setTags(paramsArray:StmtBindParams): Promise<void>
paramsArray: Tags data.TDWebSocketClientError if connection fails.async bind(paramsArray:StmtBindParams): Promise<void>
paramsArray: Binding data.TDWebSocketClientError if connection fails.async batch(): Promise<void>
TDWebSocketClientError if connection fails.async exec(): Promise<void>
TDWebSocketClientError if connection fails.getLastAffected()
async close(): Promise<void>
TDWebSocketClientError if connection fails.static async newConsumer(wsConfig:Map<string, any>):Promise<WsConsumer>
wsConfig: Consumer property configuration.TDWebSocketClientError error if an exception occurs during execution.async subscribe(topics: Array<string>, reqId?:number): Promise<void>
topics: List of topics to subscribe.reqId: Request ID, optional, used for issue tracking.TDWebSocketClientError exception on failure.async unsubscribe(reqId?:number): Promise<void>
reqId: Request ID, optional, used for issue tracking.TDWebSocketClientError exception on failure.async poll(timeoutMs: number, reqId?:number):Promise<Map<string, TaosResult>>
timeoutMs: Polling timeout in milliseconds.reqId: Request ID, optional, used for issue tracking.Map<string, TaosResult> Data corresponding to each topic.TDWebSocketClientError exception on failure.async subscription(reqId?:number):Promise<Array<string>>
reqId: Request ID, optional, used for issue tracking.Array<string> List of topics.TDWebSocketClientError exception on failure.async commit(reqId?:number):Promise<Array<TopicPartition>>
reqId: Request ID, optional, used for issue tracking.Array<TopicPartition> Consumption progress for each topic.TDWebSocketClientError exception on failure.async committed(partitions:Array<TopicPartition>, reqId?:number):Promise<Array<TopicPartition>>
partitions: An Array<TopicPartition> parameter, representing the set of partitions to query.reqId: Request ID, optional, used for issue tracking.Array<TopicPartition>, the last committed offsets for a set of partitions.TDWebSocketClientError exception if an error occurs while retrieving committed offsets.async seek(partition:TopicPartition, reqId?:number):Promise<void>
partition: A TopicPartition parameter, representing the partition and the offset to set.reqId: Request ID, optional, used for issue tracking.TDWebSocketClientError exception if an error occurs while setting the offset.async positions(partitions:Array<TopicPartition>, reqId?:number):Promise<Array<TopicPartition>>
partitions: An Array<TopicPartition> parameter, representing the partitions to query.reqId: Request ID, optional, used for issue tracking.Array<TopicPartition>, the current offsets for a set of partitions.TDWebSocketClientError exception if an error occurs while retrieving offsets.async seekToBeginning(partitions:Array<TopicPartition>):Promise<void>
partitions: An Array<TopicPartition> parameter, representing the set of partitions to operate on.TDWebSocketClientError exception if an error occurs while setting the offset.async seekToEnd(partitions:Array<TopicPartition>):Promise<void>
partitions: An Array<TopicPartition> parameter, representing the set of partitions to operate on.TDWebSocketClientError exception if an error occurs while setting the offset.async assignment(topics?:string[]):Promise<Array<TopicPartition>>
topics: Partitions to retrieve (optional), if not specified, retrieves all partitions.Array<TopicPartition>, the currently assigned partitions for the consumer.TDWebSocketClientError exception if an error occurs while retrieving assigned partitions.async close():Promise<void>
TDWebSocketClientError exception on failure.