Search code examples
node.jstime-seriesinfluxdbinfluxdb-2

How to query data from InfluxDB using Node.js


I am working on a project where I have an InfluxDB bucket that has a measurement of elapsedtime and a tag of service. I want to query Influx to be able to get all datapoints in the last 1 hour for foobar as the service. Ideally I will add a time measurement later on which I could use to base my 1 hour off since the system that gets the elapsed time and the system that writes it to Influx are different and have about 1-2 minutes of latency between them.

I have taken some example code from here and I have gotten this which is nearly identical since I am unsure of what needs to change and could not understand the documentation (head's cloudy?).

The end goal of this is to be able to have a graph that shows the elapsedtime for a service when I query my application - which queries Influx. I would like to be able to query based off a preset list of service and times but that is application side of things and I am giving here as context to what I'd like this to result in eventually.

...
variables that define bucket, url, org and token
...
const queryApi = new InfluxDB({url, token}).getQueryApi(org)
const fluxQuery =
  `from(bucket:"${bucket}") |> range(start: 0) |> filter(fn: (r) => r._measurement == "elapsedTime")`

console.log('*** QUERY ROWS ***')
// Execute query and receive table metadata and rows.
// https://v2.docs.influxdata.com/v2.0/reference/syntax/annotated-csv/
queryApi.queryRows(fluxQuery, {
  next(row: string[], tableMeta: FluxTableMetaData) {
    const o = tableMeta.toObject(row)
    console.log(
      `${o._time} ${o._measurement} in '${o.location}' (${o.example}): ${o._field}=${o._value}`
    )
  },
  error(error: Error) {
    console.error(error)
  },
  complete() {
    console.log('\nFinished SUCCESS')
  },
})

When I run this I get an error about an extra value in there however I'd expect the example to have correct code so maybe I am missing something I need to update?

  next(row: string[], tableMeta: FluxTableMetaData) {
          ^

SyntaxError: Unexpected token ':'
    at wrapSafe (internal/modules/cjs/loader.js:992:16)
    at Module._compile (internal/modules/cjs/loader.js:1040:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
    at Module.load (internal/modules/cjs/loader.js:941:32)
    at Function.Module._load (internal/modules/cjs/loader.js:782:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47

Solution

  • The issue ended up being that the code I had copied was TypeScript which as you can imagine doesn't work in a JavaScript file. Silly mistake on my end