Tuesday, July 15, 2014

a baby node server

A year and a half ago I made a node.js 101 post that turned out useful as I tried to make a little babyserver letting us here experiment with datatables outside of our heavy weight angular / Java server environment.

It looks like express.js, the library I used, has added a router(), so I decided to use that, and there's enough other new stuff to justify this blog post.

The upshot is: every request to /sites?count=###&offset=### will return an array of size "count". Each array entry is a map with key rownum (a row number starting at "offset") and rowNumber, which is the same information but with each digit turned into its word form. Any other request will attempt to serve content from the public/ folder under baby.js' working folder.

Here's the package.json:
{
  "name": "babyserver",
  "description": "a server for counting",
  "version": "0.0.1",
  "private": true,
  "dependencies": {
    "express": "4.x"
  }
}

After you have node installed, put that in an appropriately named folder, go to it, and run "npm install"

Here is baby.js:
var express = require('express');
var app = express();

var router = express.Router(); 
router.use(express.static(__dirname + '/public'));

//sites?offset=0&count=150

app.get('/sites',function(req, res) {
         res.type('application/json');
        var result = [];
        for(var i = 0; i < req.query['count']; i++){
            var d = i + parseInt(req.query['offset']);
            result.push({"rownum":d,"rowNumber":int2DigitWords(d)});
        }
res.send(result);
});

app.use('/',router);

app.listen(3000);
console.log('Listening on port 3000');

var digits = ['zero','one','two','three','four','five','six','seven','eight','nine'];

function int2DigitWords(num){
   var res = "", sep = "";
   var numString = num.toString();
   for(var i = 0; i < numString.length; i++){
      res += sep + digits[numString.substring(i,i+1)];
      sep = " ";
   } 
   return res;
}

Once that's in place, you can run "node baby.js" (or "nodemon baby.js") 
Then, I made a public/ folder and added this test.html that is a trivial jQuery table builder calling the main server:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>baby tester</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
function go(){
    $.ajax({
      url:
      "/sites?offset="+$("#offset").val()+"&count="+$("#count").val(),
      type: "get",
      dataType: "json",
      success: function(response) {
          populateTable(response)
      },
      error: function(e){
          alert("ERROR\n\n"+JSON.stringify(e,null," "));
      }
  });
}

function populateTable(res){
    var jqoTable = $("#mainTable");
    jqoTable.empty();
    for(var i = 0; i < res.length; i++){
        var row  = res[i];
        jqoTable.append("<tr><td>"+row.rownum+"</td><td>"+row.rowNumber+"</td></tr>");
    }
}

</script>
</head>
<body>
count:<input id="count" value="30"> offset:<input id="offset" value="10"><button onClick="go()">go</button>
<table border="1" id="mainTable"></table>
</body>
</html>

No comments:

Post a Comment