3.0 KiB
title | description | menu | influxdb/v2/tags | weight | aliases | |||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Query data with the InfluxDB JavaScript client library | Use the JavaScript client library to query data with the InfluxDB API in Node.js. |
|
|
201 |
|
Use the InfluxDB JavaScript client library in a Node.js environment to query InfluxDB.
The following example sends a Flux query to an InfluxDB bucket and outputs rows from an observable table.
Before you begin
Query InfluxDB
-
Change to your new project directory and create a file for your query module.
cd influx-node-app && touch query.js
-
Instantiate an
InfluxDB
client. Provide your InfluxDB URL and API token. Use thegetQueryApi()
method of the client. Provide your InfluxDB organization ID to create a configured query client.import { InfluxDB, Point } from '@influxdata/influxdb-client' const queryApi = new InfluxDB({YOUR_URL, YOUR_API_TOKEN}).getQueryApi(YOUR_ORG)
Replace the following:
YOUR_URL
: InfluxDB URLYOUR_API_TOKEN
: InfluxDB API tokenYOUR_ORG
: InfluxDB organization ID
-
Create a Flux query for your InfluxDB bucket. Store the query as a string variable. {{% warn %}} To prevent SQL injection attacks, avoid concatenating unsafe user input with queries. {{% /warn %}}
const fluxQuery = 'from(bucket: "YOUR_BUCKET") |> range(start: 0) |> filter(fn: (r) => r._measurement == "temperature")'
Replace
YOUR_BUCKET
with the name of your InfluxDB bucket. -
Use the
queryRows()
method of the query client to query InfluxDB.queryRows()
takes a Flux query and an RxJS Observer object. The client returns table metadata and rows as an RxJS Observable.queryRows()
subscribes your observer to the observable. Finally, the observer logs the rows from the response to the terminal.const observer = { next(row, tableMeta) { const o = tableMeta.toObject(row) console.log( `${o._time} ${o._measurement} in '${o.location}' (${o.sensor_id}): ${o._field}=${o._value}` ) } } queryApi.queryRows(fluxQuery, observer)
Complete example
{{% get-shared-text "api/v2.0/query/query.mjs" %}}
To run the example from a file, set your InfluxDB environment variables and use node
to execute the JavaScript file.
export INFLUX_URL=http://localhost:8086 && \
export INFLUX_TOKEN=YOUR_API_TOKEN && \
export INFLUX_ORG=YOUR_ORG && \
node query.js
{{% api/v2dot0/nodejs/learn-more %}}