Build a NodeJS App

Install the pg driver

Install the NodeJS driver using the following command. You can find further details and the source for the driver here.

  1. $ npm install pg

Prerequisites

This tutorial assumes that you have:

  • installed YugabyteDB and created a universe. If not, please follow these steps in the Quick Start guide.
  • installed a recent version of node. If not, you can find install instructions here.

We will be using the async JS utility to work with asynchronous Javascript. Install this by running the following command:

  1. $ npm install --save async

Sample JavaScript code

Create a file yb-ysql-helloworld.js and add the following content to it.

  1. var pg = require('pg');
  2. const async = require('async');
  3. const assert = require('assert');
  4. var conString = "postgres://[email protected]:5433/postgres";
  5. var client = new pg.Client(conString);
  6. async.series([
  7. function connect(next) {
  8. client.connect(next);
  9. },
  10. function createTable(next) {
  11. // The create table statement.
  12. const create_table = 'CREATE TABLE employee (id int PRIMARY KEY, ' +
  13. 'name varchar, ' +
  14. 'age int, ' +
  15. 'language varchar);';
  16. // Create the table.
  17. console.log('Creating table employee');
  18. client.query(create_table, next);
  19. },
  20. function insert(next) {
  21. // Create a variable with the insert statement.
  22. const insert = "INSERT INTO employee (id, name, age, language) " +
  23. "VALUES (1, 'John', 35, 'NodeJS');";
  24. // Insert a row with the employee data.
  25. console.log('Inserting row with: %s', insert)
  26. client.query(insert, next);
  27. },
  28. function select(next) {
  29. // Query the row for employee id 1 and print the results to the console.
  30. const select = 'SELECT name, age, language FROM employee WHERE id = 1;';
  31. client.query(select, function (err, result) {
  32. if (err) return next(err);
  33. var row = result.rows[0];
  34. console.log('Query for id=1 returned: name=%s, age=%d, language=%s',
  35. row.name, row.age, row.language);
  36. next();
  37. });
  38. }
  39. ], function (err) {
  40. if (err) {
  41. console.error('There was an error', err.message, err.stack);
  42. }
  43. console.log('Shutting down');
  44. client.end();
  45. });

Run the application

To run the application, type the following:

  1. $ node yb-ysql-helloworld.js

You should see the following output.

  1. Creating table employee
  2. Inserting row with: INSERT INTO employee (id, name, age, language) VALUES (1, 'John', 35, 'NodeJS');
  3. Query for id=1 returned: name=John, age=35, language=NodeJS
  4. Shutting down