Monday, 26 January 2015

Up and running with the node Oracle driver on Ubuntu

Dan McGhan did a great video guide on getting set up with Node.js and the Oracle driver, which you can check here:



Installing Node

As an alternative method to downloading the node.js tarball as per the video, you can just install using your package manager:

sudo apt-get install nodejs npm

Once installed, you can access the node interpreter with the command `nodejs`:


Post install, you should set the NODE_PATH environment variable so that nodejs can find any modules you install:

export NODE_PATH=/usr/local/lib/node_modules

This is where the node-oracledb driver gets installed to.

Installing the Oracle driver


wget https://github.com/oracle/node-oracledb/archive/master.zip -O node-oracledb.zip
unzip node-oracledb.zip
cd node-oracledb-master
sudo npm install -g

Once all that is done, you can get rid of those files:

cd ~
rm node-oracledb.zip
rm -rf node-oracledb-master

Then, we can get to the example files:

cd $NODE_PATH/oracledb/examples

First, update the dbConfig.js with appropriate connection properties, then test with:

nodejs connect.js

You should see: Connection was successful!

Shell script

You can then make a shell script on this. E.g. you may have a job logging database that you want to notify users to whenever they enter a console (assuming the username matches):

userjobs.sh:

#!/usr/bin/env nodejs
var oracledb = require('oracledb');
var dbConfig = require('./dbconfig.js');

oracledb.getConnection(
  {
    user          : dbConfig.user,
    password      : dbConfig.password,
    connectString : dbConfig.connectString
  },
  function(err, connection)
  {
    if (err) {
      console.error(err.message);
      return;
    }
    connection.execute(
      "SELECT count(1) "
    + "FROM jobs "
    + " WHERE status = :jobStatus"
    + " and lower(assigned) = lower(:userName)",
      ["Open", process.env.USER],
      function(err, result)
      {
        if (err) {
          console.error(err.message);
          return;
        }
        rowCount = result.rows[0][0];
        console.log("You have " + rowCount + " jobs awaiting your attention.")
      });
  });



Make it executable

chmod +x userjobs.sh
./userjobs.sh
You have 1 jobs awaiting your attention.