Create a Node App with CockroachDB

Introduction

This tutorial will explain how to create a simple node app with a CockroachDB cluster. Node.js is an open source program written in JavaScript designed for writing scalable internet applications. It is used for developing networking and server-side applications and can be run on Mac, Linux and Windows machines.

Prerequisites

  • CockroachDB must be installed and running on the system. To obtain the currently installed version of CockroachDB, execute the command cockroach version in the terminal for Linux and MacOS systems or in the command prompt for Windows based machines.

  • The Node.JS and the NPM, or the Node package manager, must be installed and working to create a Node app with CockroachDB.

Install Node.JS

Installation of the node.JS is required before an application with CockroachDB can be created. For a Windows or MacOS device, click the download link for the installer for node.

Install Node on MacOS with Homebrew

Homebrew’s brew package manager can be used as well on MacOS by executing the following command:

1
brew install node

Install Node on Linux systems

For Ubuntu or Debian distro of Linux uses the APT-GET repository as follows to install Node.JS and NPM:

1
sudo apt-get install nodejs

If using a Fedora or CentOS in a red hat distro of Linux, use the YUM command as follows:

1
sudo yum install nodejs

Verify that Node and NPM are installed

Node and its package manager should now be installed and working properly. Use the node -v and npm -v commands to verify the installation of each to determine the respective version numbers.

Node’s NPM package manager can also be installed globally by using the -g flag in the following command:

1
sudo npm install npm -g

Setting up the Node app

Create a new directory in the terminal or command-prompt window that will serve for the Node app. Execute the command mkdir and change it into the directory using cd.

Now run the command npm init -y for the (package.json) file for the Node app.

Install NPM for packages

The pg Node.js driver for Postgres is required for executing the following example. It uses the NPM’s i, or install, command shown here:

1
npm i pg

The pg module allows for communication and making API requests to Postgres from within the Node application.

Install the async library with the following command:

1
npm i async

The asynchronous JavaScript library permits running multiple promises and callback processes simultaneously. This is designed to prevent a bottleneck in the application due to pending processes.

Start the CockroachDB cluster

The following code will start the cluster using the SQL built in shell, create the user database and other queries:

1
2
3
4
5
cockroach start-single-Node \
--insecure \
--listen-addr=localhost:26257 \
--http-addr=localhost:8080 \
--background

Here is a breakdown of the above code:

  • The start-single-node is a quick way to create a single-node cluster for testing the application and making use of SQL queries inside the SQL shell.

  • --insecure is a flag that doesn’t require certificate validation for deployment and can be used on anything the user can access. For example, it allows for logging in without requiring a password because there is no encryption or authentication needed and has no confidentiality.

  • The --listen-addr is used to connect the IP address or the hostname from the clients. The default IP address is 26257.

  • --http-addr is used for admin to pull requests to the user interface of the port in HTTP. The default for the http-addr is port 8080

  • The --background is set for the command to run in the background and takes control of everything in the shell after the node is properly prepared to accept requests.

Use SQL’s built-in shell

A user and a database is created with the following command to set the node.JS credentials:

1
cockroach SQL --insecure

Once the user and a database is created and connected to a defaultdb in root 26257, create a user with the following command:

1
2
3
4
root@:26257/defaultdb- CREATE USER IF NOT EXISTS orkb;
CREATE USER 1

TIME: 267.689185ms

NOTE: In the above example, IF NOT EXISTS is used to determine whether the user ‘orkb’ already exists, the system will return an error.

Now execute the following command to create a database for deployment of the Node app:

1
2
3
4
root@:26257/defaultdb- CREATE DATABASE somedb;
CREATE DATABASE

TIME: 497.134123ms

Finally, set database privileges for the user created earlier with the following command:

1
2
3
4
root@:26257/defaultdb- GRANT ALL ON DATABASE somedb TO orkb;
GRANT

TIME: 168.701051ms

Create the Node app

An IDE having JavaScript syntax support, such as Atom, Visual Studio Code, or Sublime, is required in order edit and save the code for the application’s .js files before the Node application can be started,

Create the Node app’s JavaScript file

First, create a file that contains the name app.js. This can be done in a terminal window with subl app.js for Sublime or code app.js for VS Code.

Require the Node modules

Create an instance variable of the node application for the configuration of the database in CockroachDB using the following code:

1
2
3
4
//Using the pg driver helps the constant variable to communicate to the CockroachDB
var async = require("async");
var fs = require("fs");
var pg = require("pg");

Connect to the CockroachDB cluster

Configure the database credentials in CockroachDB, using the currently set port, when starting the local cluster in CockroachDB. Connect to the database using the following command:

1
2
3
4
5
6
7
// Connection to the database
var config = {
  user: "orkb",
  host: "localhost",
  database: "somedb",
  port: 26257
};

With the connection to the database established, execute the following code to create a table, insert some queries and print the output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Pass the configurations of the pool to the client once its created
var pool = new pg.Pool(config);
pool.connect(function (err, client, done) {

    // Close the connection to the database and exit
    var finish = function () {
        done();
        process.exit();
    };

    if (err) {
        console.error('Error connecting to the CockroachDB', err);
        finish();
    }

Following is waterfall script used to create a task that will have a second function instantly follow the first function once the first function is deployed:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
    // async.waterfall is used to run a multiple task that is dependent to the previous one.
    async.waterfall([
        function (next) {
            // Create the an 'demo' table
            client.query('CREATE TABLE IF NOT EXISTS demo (id INT PRIMARY KEY, string_txt TEXT NOT NULL);', next);
        },
        function (results, next) {
            // Insert three rows into the 'demo' table.
            client.query("INSERT INTO demo(id, string_txt) VALUES (1, 'Hello Guys!'), (2, 'Hows it going?'), (3, 'Kamusta na');", next);
        },
        function (results, next) {
            // Print the record inserted into the table
            client.query('SELECT id, string_txt FROM demo;', next);
        },
    ],
    function (err, results) {
        if (err) {
            console.error('Error Inserting and Printing demo table: ', err);
            finish();
        }

        console.log('demo App with CockroachDB:');
        results.rows.forEach(function (row) {
            console.log(row);
        });

        finish();
    });
});

Start the Node application

First save the file and then execute the script for the Node application in a terminal using the following node command:

1
2
3
4
5
linux@linux-NECq:~/Desktop/node-app$ node app.js
demo App WITH CockroachDB:
{ id: '1', string_txt: 'Hello Guys!' }
{ id: '2', string_txt: 'Hows it going?' }
{ id: '3', string_txt: 'Kamusta na' }

Conclusion

This tutorial covered how to create a simple node app with a CockroachDB cluster. The article specifically explained how to install Node.JS on Linux and MacOS systems, how to verify that Node and NPM were successfully installed, set up and create the Node app and start the CockroachDB cluster. The tutorial also covered how to use SQL’s built-in shell, create the Node app’s JavaScript file, connect to the CockroachDB cluster and start the Node application. Remember that an IDE having JavaScript syntax support is required to edit and save the code before the Node application can be started.

Just the Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//Using the pg driver helps the constant variable to communicate to the CockroachDB
var async = require("async");
var fs = require("fs");
var pg = require("pg");

// Connection to the database
var config = {
  user: "orkb",
  host: "localhost",
  database: "somedb",
  port: 26257
};

// Pass the configurations of the pool to the client once its created
var pool = new pg.Pool(config);
pool.connect(function(err, client, done) {
  // Close the connection to the database and exit
  var finish = function() {
    done();
    process.exit();
  };

  if (err) {
    console.error("Error connecting to the CockroachDB", err);
    finish();
  }

  // async.waterfall is used to run a multiple task that is dependent to the previous one.
  async.waterfall(
    [
      function(next) {
        // Create the an 'demo' table
        client.query(
          "CREATE TABLE IF NOT EXISTS demo (id INT PRIMARY KEY, string_txt TEXT NOT NULL);",
          next
        );
      },
      function(results, next) {
        // Insert three rows into the 'demo' table.
        client.query(
          "INSERT INTO demo(id, string_txt) VALUES (1, 'Hello Guys!'), (2, 'Hows it going?'), (3, 'Kamusta na');",
          next
        );
      },
      function(results, next) {
        // Print the record inserted into the table
        client.query("SELECT id, string_txt FROM demo;", next);
      }
    ],
    function(err, results) {
      if (err) {
        console.error("Error Inserting and Printing demo table: ", err);
        finish();
      }

      console.log("demo App with CockroachDB:");
      results.rows.forEach(function(row) {
        console.log(row);
      });

      finish();
    }
  );
});

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.