Building web server with Node.js

2 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.

Starting script

# Run in the background
nohup $HOME/node/bin/node $HOME/www/docs/myweb.js &

# Run in the background with forever
$HOME/node/node_modules/forever/bin/forever -l myweb.js.log -a start $HOME/www/docs/myweb.js

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