image of long windy road

Embark on a new journey with node-influx!

When in doubt, start at the beginning—an adage that applies to any learning journey, including getting started with the node-influx client library. Let’s take a look at the InfluxDB client librariesin particular, node-influx, an InfluxDB client for JavaScript users. This client library features a simple API for most InfluxDB operations and is fully supported in Node and the browser, all without needing any extra dependencies.

There’s a great tutorial for the node-influx library available online as well as some handy documentation, which I recommend reading through beforehand. Here, we will just cover a few of the basics.

What You’ll Need

For this tutorial, I’ll be running a local installation of InfluxDB; you can learn how to get that up and running here. You’ll also need Node installed. If Node.js is not your cup of tea, there are plenty of other client libraries to work with and several guides on using InfluxDB with other languages available, such as these posts on Python and Ruby.

Set the Scene

Image of two surfers walking into the ocean

How to get slotted

Let us imagine for a minute you have an inexplicable love for surfing. You find yourself in Hawaii—on a journey following in Duke’s footsteps—and you’re trying to find the best surf spot. And the best time at which to surf said amazing spot. Makes sense to take a look at the tides right? Well, according to our trusty friend Wikipedia, ocean tides are a great example of time series data. They ebb and flow over time (yes, I know I’m laying it on rather thick here). So let’s practice putting some sample tide data into InfluxDB using the node-influx library and see what happens.

First things first, we need to install the node-influx library in the application folder where it will be used.

$ npm install --save influx

This adds the node-influx library to our node_modules; we also need to require the library into our server file, like so

const Influx = require('influx');

We’ll use the following constructor function to connect to a single InfluxDB instance and specify our connection options.

const influx = new Influx.InfluxDB({
  host: 'localhost',
  database: 'ocean_tides',
  schema: [
    {
      measurement: 'tide',
      fields: { height: Influx.FieldType.FLOAT },
      tags: ['unit', 'location']
    }
  ]
});

There are a few different options available here:

  • You could connect to a single host by passing the DSN as a string into the constructor argument, like so:
const influx = new Influx.InfluxDB('http://user:[email protected]:8086/database')
  • You could also pass in a full set of config details and specify properties such as username, password, database, host, port, and schemathat’s what we did above.
  • If you have multiple Influx nodes to connect to, you can pass in a cluster config. For example:
    const client = new InfluxDB({
      database: 'my_database',
      username: 'duke_kahanamoku',
      password: 'aloha',
      hosts: [
        { host: 'db1.example.com' },
        { host: 'db2.example.com' },
      ]
      schema: [
        {
          measurement: 'tide',
          fields: { height: Influx.FieldType.FLOAT },
          tags: ['unit', 'location']
        }
      ]
    })

It’s worth noting here that within your schema design, you will need to designate the FieldType for your field values using Influx.FieldType—they can be strings, integers, floats, or booleans.

Checking The Database

We can use influx.getDatabaseNames() to first check if our database already exists. If it doesn’t, we can then use influx.createDatabase() to create our database. See below:

influx.getDatabaseNames()
  .then(names => {
    if (!names.includes('ocean_tides')) {
      return influx.createDatabase('ocean_tides');
    }
  })
  .then(() => {
    app.listen(app.get('port'), () => {
      console.log(`Listening on ${app.get('port')}.`);
    });
    writeDataToInflux(hanalei);
    writeDataToInflux(hilo);
    writeDataToInflux(honolulu);
    writeDataToInflux(kahului);
  })
  .catch(error => console.log({ error }));

We are first grabbing all the databases available from our connected Influx instance, and then cycling through the returned array to see if any of the names match up with ‘ocean_tides’. If none do, then we create a new database with that name. The callback from that then writes our data into the database.

Writing Data to InfluxDB

Using influx.writePoints(), we can write our data points into the database.

influx.writePoints([
      {
        measurement: 'tide',
        tags: {
          unit: locationObj.rawtide.tideInfo[0].units,
          location: locationObj.rawtide.tideInfo[0].tideSite,
        },
        fields: { height: tidePoint.height },
        timestamp: tidePoint.epoch,
      }
    ], {
      database: 'ocean_tides',
      precision: 's',
    })
    .catch(error => {
      console.error(`Error saving data to InfluxDB! ${err.stack}`)
    });

To keep things simple, I just pulled in a few sample data files, then loop through them by location and write each data point to InfluxDB under the measurement name tide with location and unit tags (both are strings). There is only one field here, height and I send in a timestamp as well, although that is not technically required (it’s more accurate though). You can specify additional options such as the database to write to, the time precision, and the retention policy.

Querying the Database

We’ve learned how to write data into the database; now we need to know how to query for that data. It’s simplewe can use influx.query() and pass in our InfluxQL statement to retrieve the data we want.

influx.query(`
    select * from tide
    where location =~ /(?i)(${place})/
  `)
  .then( result => response.status(200).json(result) )
  .catch( error => response.status(500).json({ error }) );

Here we are querying the database for any data from measurement tide where location contains the place name passed in (using a regular expression). If you’ve stored a lot of data, it’s a good idea to also limit your query to a certain time span. You can additionally pass in an options object (database, retention policy, and time precision) to the influx.query() method.

Conclusion

That covers all the basics for the node-influx client library. Have a scan over the docs and let us know if there are other use cases you’d like to hear about! I’ve also posted all this code in a repository on GitHub if you want to try it out for yourself. Questions and comments? Reach out to us on Twitter: @mschae16 or @influxDB. Now go forth and find that monster wave—surf’s up!

image of man making aloha gesture in ocean

Aloha

X
Contact Sales