Building web server with Node.js

3 minute read

You can easily build the web server with Node.js on the Linux or Unix. I’ve used it to build a monitoring web server. You can gather monitoring data by selecting them from database and also receive udp data directly. The following examples are simple code snippets that help build your monitoring web server.

Business logic and web views were omitted. I recommend to use web frameworks such as angular.js, react.js or knockout.js to build your web views.

Requirements

I will set up node on linux. First, you need to have Node and npm installed.

cat /etc/redhat-release
CentOS Linux release 7.6.1810 (Core) 

node -v
v6.17.1

npm -v
3.10.10

# create a package.json file that will keep track of our project dependencies and allow us to do some cool things later on.
npm init -y

# adding in the Express framework. (express@4.17.1)
npm install express

npm install oracledb
oracledb ERR! NJS-069: node-oracledb 4.2.0 requires Node.js 8.16 or later
oracledb ERR! An older node-oracledb version may work with Node.js v6.17.1

How to install Older versions of node-oracledb (1) npm view oracledb versions (2) npm install oracledb@3.1.2

Error: DPI-1047: Cannot locate a 64-bit Oracle Client library: “libclntsh.so: cannot open shared object file: No such file or directory”. See https://oracle.github.io/odpi/doc/installation.html#linux for help Node-oracledb installation instructions: https://oracle.github.io/node-oracledb/INSTALL.html You must have 64-bit Oracle client libraries in LD_LIBRARY_PATH, or configured with ldconfig. If you do not have Oracle Database on this computer, then install the Instant Client Basic or Basic Light package from http://www.oracle.com/technetwork/topics/linuxx86-64soft-092277.html

Express is the Node.js framework we will use to create the actual API endpoints, so we will need to install that package. The node_modules folder is where the Express framework code lives as well as all its dependencies.

Simple example of app.js

const express = require("express");

const PORT = 8088;
const app = express();

app.get("/hello", (req, res) => {
  res.send("Hello world");
});

app.listen(PORT, () => {
 console.log(`Server is listening on port: ${PORT}`);
});

Starting Node.js

# starting nodejs in forground for testing
node app.js

# checking on linux
curl localhost:8088/hello

Example of starting script

# Run in the background
nohup node app.js &

# Run in the background with forever
CHOME=`pwd`
forever start -l $HOME/app.js.log -a app.js

If you do not set the log path, it will use $HOME/.forever as its home directory.
# start
forever -help
forever list
forever start app.js
forever stop
forever stopall
forever restart
forever logs

Another daemon PM2

npm install pm2 -g
pm2 version
pm2 start app.js

PM2

Simple Example (myweb.js)

// ------------------------------
// Common functions
// ------------------------------
function getCurrTime()
{
  var _time = new Date();
  var ctime = _time.toISOString().substring(1,10) + " " + _time.toTimeString().substring(0,8) + " ";
  return ctime;
}

//setInterval(your_func, 5000);

// ------------------------------
// STARTING...
// ------------------------------
console.log("===========================================");
console.log(getCurrTime() + 'STARTING...');

// ------------------------------
// ORACLE DB
// ------------------------------
var oracledb = require('oracledb');
var CONNECTION = null;

function get_new_connection()
{
  oracledb.getConnection(
    {
      user: "yourdbuserid",
      password: "yourdbpass",
      connectionString: "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(Host=127.0.0.1)(Port=1521)(CONNECT_DATA=(SID=yourdbsid)))"
    },
    function (err, connection)
    {
      if (err) {
        console.error(err);
        CONNECTION = null;
        return;
      }

      CONNECTION = connection;
    }
  )
}

// ------------------------------
// UDP Listening
// ------------------------------
var UDP_PORT = 1234;
var UDP_HOST = '0.0.0.0';
var dgram = requires('dgram');
var myudp = dgram.createSocket('udp4');

myudp.on('listening', function() {
  var address = myudp.address();
  console.log(getCurrTime() + 'UDP Server listening on ' + address.port);
});

myudp.on('message', function(msg, remote) {
  msg = iconv.decode(new Buffer(msg), 'EUC-KR');
  myapi.setMessage(msg);
});

myudp.bind(UDP_PORT, UDP_HOST);)

// ------------------------------
// HTTP Listening
// ------------------------------
var WEB_PORT=8088

var express = require('express');
// var session = require('express-session');
var http = require('http');
var path = require('path');
var iconv = requires('iconv-lite')
var routes = require('./routes');
var myapi = requires('./routes/myapi');

var app = express();

app.set('port', process.env.PORT || WEB_PORT);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');

app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
//app.use(express.session());

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/myapi', myapi.start);

http.createServer(app).listen(app.get('port'), function() {
  console.log(getCurrTime() + 'Express server listening on port ' + app.get('port'));
  console.log('==============================================');
});

Example(routes/myapi.js)

var exec = require("child_process").exec;
var MESSAGE = {};

exports.setMessage = function(data) {
  // Parse data and create a new message to copy to MESSAGE
  // The MESSAGE may be used to respond to a request.
  // (It's good to use data forms such as json.)
};

exports.start = function(request, response) {
  if (request.query.type == "aaa") {

  } else {

  }
  response.writeHead(200, {"Content-Type": "text/html;charset=UTF-8"});
  response.write(JSON.stringify(MESSAGE, null, 4));
  response.end();
};

Tags:

Categories:

Updated:

Leave a comment