Connecting to your database with the DataStax Node.js driver

Use the DataStax Node.js driver to connect to your database created using the DataStax Constellation console.

Use the DataStax Node.js driver to connect to your Apollo database and begin building your own application.
Tip: DataStax recommends using the DataStax Node.js driver for Apache Cassandra. You can also use the DataStax Enterprise (DSE) Node.js driver, which exposes the same API for connecting to Cassandra databases.

Prerequisites

  1. Download and install a current Node.js LTS version with npm.
  2. Create a DataStax Apollo database.
  3. Download the secure connect bundle to obtain connection credentials for your database.

Procedure

  1. Install the DataStax Node.js driver:
    • DataStax Node.js driver for Apache Cassandra

      npm install cassandra-driver
    • DSE driver

      npm install dse-driver
  2. Create a connect-database.js file in the main directory for your Node.js project.
    cd nodejsProject
    touch connect-database.js
  3. Copy the following connection code into the connect-database.js file.
    Note: Include the absolute path to the secure connect bundle for your Cassandra database (secure-connect-database_name.zip) in the secureConnectBundle parameter, as shown in the following examples.
    • DataStax Node.js driver for Apache Cassandra

      'use strict'
      
      const { Client } = require('cassandra-driver');
    • DSE Node.js driver

      'use strict'
      
      const { Client } = require('dse-driver');
  4. After the Client class, add the following code to connect-database.js. This code creates a Client instance to connect to your Apollo database, runs a CQL query, and prints the output to the console.
    async function run() {
      const client = new Client({
        cloud: { secureConnectBundle: 'path/to/secure-connect-database_name.zip' },
        credentials: { username: 'username', password: 'password' }
      });
    
      await client.connect();
    
      // Execute a query
      const rs = await client.execute('SELECT * FROM system.local');
      console.log(`Hello from cluster: ${rs.first()['cluster_name']}`);
    
      await client.shutdown();
    }
    
    // Run the async function
    run();
  5. Save and close the connect-database.js file.
  6. Run the connect-database.js example with the Node.js runtime:
    node connect-database.js

    The console output displays the cluster_name value from the system.local table.

What's next

Build your application. See the DataStax Node.js driver for Apache Cassandra and DSE Node.js driver documentation for more information about using the DataStax Node.js driver.