homework-jianmu/docs/en/14-reference/05-connectors/35-node.mdx

338 lines
14 KiB
Plaintext

---
title: TDengine Node.js Client Library
sidebar_label: Node.js
description: This document describes the TDengine Node.js client library.
toc_max_heading_level: 4
---
import Tabs from "@theme/Tabs";
import TabItem from "@theme/TabItem";
import RequestId from "./_request_id.mdx";
`@tdengine/websocket` is the official Node.js client library for TDengine. Node.js developers can develop applications to access the TDengine instance data.
The source code for the Node.js client library is hosted on [GitHub](https://github.com/taosdata/taos-connector-node/tree/main).
## Connection types
Node.js connector supports only websocket connection through taosAdapter.
For a detailed introduction of the connection types, please refer to: [Establish Connection](../../../develop/connect/#establish-connection)
## Supported platforms
Node.js client library needs to be run with Node.js 14 or higher version.
## Recent update logs
| Node.js connector version | major changes | TDengine 版本 |
| :-----------------------: | :------------------: | :----------------:|
| 3.1.0 | new version, supports websocket | 3.2.0.0 or later |
## Supported features
1. Connection Management
2. General Query
3. Continuous Query
4. Parameter Binding
5. Subscription
6. Schemaless
## Handling exceptions
After an error is reported, the error message and error code can be obtained through try catch. The Node.js client library error code is between 100 and 110, while the other error codes are for the TDengine function module.
Please refer to the table below for error code, error description and corresponding suggestions.
| Error Code | Description | Suggested Actions |
| ---------- | -------------------------------------------------------------| -------------------------------------------------------------------------------------------------- |
| 100 | invalid variables | The parameter is invalid. Check the interface specification and adjust the parameter type and size.|
| 101 | invalid url | URL error, please check if the url is correct. |
| 102 | received server data but did not find a callback for processing | Client waiting timeout, please check network and TaosAdapter status. |
| 103 | invalid message type | Please check if the client version and server version match. |
| 104 | connection creation failed | Connection creation failed. Please check the network and TaosAdapter status. |
| 105 | websocket request timeout | Increase the execution time by adding the messageWaitTimeout parameter, or check the connection to the TaosAdapter.|
| 106 | authentication fail | Authentication failed, please check if the username and password are correct. |
| 107 | unknown sql type in tdengine | Check the data type supported by TDengine. |
| 108 | connection has been closed | The connection has been closed, check the connection status, or recreate the connection to execute the relevant instructions. |
| 109 | fetch block data parse fail | Please check if the client version and server version match. |
| 110 | websocket connection has reached its maximum limit | Please check if the connection has been closed after use |
## Data Type Mapping
The table below despicts the mapping between TDengine data type and Node.js data type.
| TDengine Data Type | Node.js Data Type|
|-------------------|-------------|
| 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**: Only TAG supports JSON types
## Installation Steps
### Pre-installation preparation
- Install the Node.js development environment, using version 14 or above. Download link: https://nodejs.org/en/download/
### Install Node.js client library via npm
```bash
npm install @tdengine/websocket
```
### Verify
After installing the TDengine client, use the `nodejsChecker.js` program to verify that the current environment supports Node.js access to TDengine.
Verification in details:
- Create an installation test folder such as `~/tdengine-test`. Download the [nodejsChecker.js](https://github.com/taosdata/TDengine/tree/main/docs/examples/node/websocketexample/nodejsChecker.js) to your local machine.
- Execute the following command from the command-line.
```bash
npm init -y
npm install @tdengine/websocket
node nodejsChecker.js host=localhost
```
- After executing the above steps, the command-line will output the result of `nodejsChecker.js` connecting to the TDengine instance and performing a simple insert and query.
## Establishing a connection
Install and import the `@tdengine/websocket` package.
**Note**: After using the Node.js client library, it is necessary to call taos.destroy() Release connector resources.
```javascript
const taos = require("@tdengine/websocket");
//database operations......
taos.destroy();
```
```javascript
WSConfig configures the Websocket parameters as follows:
getToken(): string | undefined | null;
setToken(token: string): void;
getUser(): string | undefined | null;
setUser(user: string): void;
getPwd(): string | undefined | null;
setPwd(pws: string): void;
getDb(): string | undefined | null;
setDb(db: string): void;
getUrl(): string;
setUrl(url: string): void;
setTimeOut(ms: number): void;
getTimeOut(): number | undefined | null;
```
```javascript
{{#include docs/examples/node/websocketexample/sql_example.js:createConnect}}
```
## Usage examples
### Create database and tables
```javascript
{{#include docs/examples/node/websocketexample/sql_example.js:create_db_and_table}}
```
**Note**: If you do not use `USE power` to specify the database, all subsequent operations on the table need to add the database name as a prefix, such as power.meters.
### Insert data
```javascript
{{#include docs/examples/node/websocketexample/sql_example.js:insertData}}
```
> NOW is an internal function. The default is the current time of the client's computer.
> `NOW + 1s` represents the current time of the client plus 1 second, followed by the number representing the unit of time: a (milliseconds), s (seconds), m (minutes), h (hours), d (days), w (weeks), n (months), y (years).
### Querying data
```javascript
{{#include docs/examples/node/websocketexample/sql_example.js:queryData}}
```
> Discovered data structure
```javascript
wsRow:meta:=> [
{ name: 'ts', type: 'TIMESTAMP', length: 8 },
{ name: 'current', type: 'FLOAT', length: 4 },
{ name: 'voltage', type: 'INT', length: 4 },
{ name: 'phase', type: 'FLOAT', length: 4 },
{ name: 'location', type: 'VARCHAR', length: 64},
{ name: 'groupid', type: 'INT', length: 4 }
]
wsRow:data:=> [
[ 1714013737536n, 12.3, 221, 0.31, 'California.SanFrancisco', 3 ]
]
```
### Execute SQL with reqId
<RequestId />
```javascript
{{#include docs/examples/node/websocketexample/sql_example.js:sqlWithReqid}}
```
### Writing data via parameter binding
The Node.js client library provides a parameter binding api for inserting data. Similar to most databases, TDengine currently only supports the question mark `?` to indicate the parameters to be bound.
**Note**: Do not use `db.?` in prepareStatement when specify the database with the table name, should directly use `?`, then specify the database in setTableName, for example: `prepareStatement.setTableName("db.t1")`.
Sample Code:
```javascript
{{#include docs/examples/node/websocketexample/stmt_example.js}}
```
The methods to set TAGS values or VALUES columns:
```javascript
setBoolean(params: any[]): void;
setTinyInt(params: any[]): void;
setUTinyInt(params: any[]): void;
setSmallInt(params: any[]): void;
setUSmallInt(params: any[]): void;
setInt(params: any[]): void;
setUInt(params: any[]): void;
setBigint(params: any[]): void;
setUBigint(params: any[]): void;
setFloat(params: any[]): void;
setDouble(params: any[]): void;
setVarchar(params: any[]): void;
setBinary(params: any[]): void;
setNchar(params: any[]): void;
setJson(params: any[]): void;
setVarBinary(params: any[]): void;
setGeometry(params: any[]): void;
setTimestamp(params: any[]): void;
```
**Note**: Only TAG supports JSON types
### Schemaless Writing
TDengine supports schemaless writing. It is compatible with InfluxDB's Line Protocol, OpenTSDB's telnet line protocol, and OpenTSDB's JSON format protocol. For more information, see [Schemaless Writing](../../schemaless/).
```javascript
{{#include docs/examples/node/websocketexample/line_example.js}}
```
### Schemaless with reqId
This reqId can be used to request link tracing.
```javascript
await wsSchemaless.schemalessInsert([influxdbData], SchemalessProto.InfluxDBLineProtocol, Precision.NANO_SECONDS, ttl, reqId);
await wsSchemaless.schemalessInsert([telnetData], SchemalessProto.OpenTSDBTelnetLineProtocol, Precision.NANO_SECONDS, ttl, reqId);
await wsSchemaless.schemalessInsert([jsonData], SchemalessProto.OpenTSDBJsonFormatProtocol, Precision.NANO_SECONDS, ttl, reqId);
```
### Data Subscription
The TDengine Node.js client library supports subscription functionality with the following application API.
#### Create a Topic
```javascript
{{#include docs/examples/node/websocketexample/tmq_example.js:create_topic}}
```
#### Create a Consumer
```javascript
{{#include docs/examples/node/websocketexample/tmq_example.js:create_consumer}}
```
**Parameter Description**
- taos.TMQConstants.CONNECT_USER: username.
- taos.TMQConstants.CONNECT_PASS: password.
- taos.TMQConstants.GROUP_ID: Specifies the group that the consumer is in.
- taos.TMQConstants.CLIENT_ID: client id.
- taos.TMQConstants.WS_URL: The URL address of TaosAdapter.
- taos.TMQConstants.AUTO_OFFSET_RESET: When offset does not exist, where to start consumption, the optional value is earliest or latest, the default is latest.
- taos.TMQConstants.ENABLE_AUTO_COMMIT: Specifies whether to commit automatically.
- taos.TMQConstants.AUTO_COMMIT_INTERVAL_MS: Automatic submission interval, the default value is 5000 ms.
- taos.TMQConstants.CONNECT_MESSAGE_TIMEOUT: socket timeout in milliseconds, the default value is 10000 ms. It only takes effect when using WebSocket type.
For more information, see [Consumer Parameters](../../../develop/tmq). Note that the default value of auto.offset.reset in data subscription on the TDengine server has changed since version 3.2.0.0.
#### Subscribe to consume data
```javascript
{{#include docs/examples/node/websocketexample/tmq_example.js:subscribe}}
```
#### Assignment subscription Offset
```javascript
{{#include docs/examples/node/websocketexample/tmq_example.js:assignment}}
```
#### Close subscriptions
```java
// Unsubscribe
consumer.unsubscribe();
// Close consumer
consumer.close()
// free connector resource
taos.destroy();
```
For more information, see [Data Subscription](../../../develop/tmq).
#### Full Sample Code
```javascript
{{#include docs/examples/node/websocketexample/tmq_example.js}}
```
## More sample programs
| Sample Programs | Sample Program Description |
| ---------------------------------------------------------------------------------------------------------------------------------| -------------------------------------- |
| [sql_example](https://github.com/taosdata/TDengine/tree/main/docs/examples/node/websocketexample/sql_example.js) | Basic operations such as establishing connections and running SQl commands.|
| [stmt_example](https://github.com/taosdata/TDengine/tree/main/docs/examples/node/websocketexample/stmt_example.js) | Binding multi-line parameter insertion. | |
| [line_example](https://github.com/taosdata/TDengine/tree/main/docs/examples/node/websocketexample/line_example.js) | Schemaless insert |
| [telnet_line_example](https://github.com/taosdata/TDengine/tree/main/docs/examples/node/websocketexample/telnet_line_example.js) | OpenTSDB Telnet insert |
| [json_line_example](https://github.com/taosdata/TDengine/tree/main/docs/examples/node/websocketexample/json_line_example.js) | OpenTSDB Json insert |
| [tmq_example](https://github.com/taosdata/TDengine/tree/main/docs/examples/node/websocketexample/tmq_example.js) | Using data subscription |
## Usage limitations
- Node.js client library (`@tdengine/websocket`) supports Node.js 14 or higher.
- It supports only WebSocket connection, so taosAdapter needs to be started in advance.
- After using the connect, you need to call taos.destroy(); Release connector resources.
## Frequently Asked Questions
1. "Unable to establish connection" or "Unable to resolve FQDN"
**Solution**: Usually, the root cause is an incorrect FQDN configuration. You can refer to this section in the [FAQ](../../../train-faq/faq/#2-how-can-i-resolve-the-unable-to-establish-connection-error) to troubleshoot.