Friday, January 17, 2014

Experimenting with Node.js

Node.js seems particularly suited for small real-time web pages where users can see event-driven data be updated on the webpage without a page refresh.  I spent a couple hours this weekend learning about node.js so I made a simple long polling web server based on one of the examples from this article.

To get my Ubuntu VM ready to do this, I did the following:
-downloaded the node-v0.10.24-linux-x64.tar.gz and untarred the package.  I had all the prereqs from the README.md file, except python
-installed python 2.7.2.  Since I hadn't used python scripting before, decided to dabble a bit in that by writing a few statements in a python script to get used to python syntax

The Simple Long Polling Web Server Example:
The node.js web server is polling every 10000 milliseconds, and if the current time in milliseconds modulus 3 is zero, then it returns the time to the caller.  A simple html webpage is making an ajax call to the node.js web server, and will append the time if conditions are satisfied.  Here's the output of it:






















Files:

  1. server_longpoll.js:
    var sys = require('sys'),
       http = require('http');
    
    http.createServer(function(request, response) {
      getTime(request, response);
    }).listen(8000);
    
    function getTime(request, response)
    {
      var now = new Date();
      var timeInMilliseconds = now.getTime();
    
      // event that is listening is: if time is modular by 3
      if ((timeInMilliseconds % 3) == 0)
      {
        // return the contents
        response.writeHead(200, {
          'Content-Type'   : 'text/plain',
          'Access-Control-Allow-Origin' : '*'
        });
    
        // return response
        response.write(timeInMilliseconds.toString());
        response.end();
    
        // return
        return false;
      }
    
      setTimeout(function() {getTime(request, response) }, 10000);
    
    };
    
  2. cherryshoe_longpoll.html:
    <head>
    <meta charset="UTF-8">
    <title>Sample ajax call to node server with long polling</title>
    </head>
    
    <body>
    Polling every 10000 milliseconds... </br>
    Current time in milliseconds where modulus 3 is zero: <div id="updateId"></div>
    
    
    <script src="jquery-1.9.1.js"></script>
    <script src="cherryshoe_longpoll.js"></script>
    </body>
    </html>
    
  3. cherryshoe_longpoll.js:
    $(document).ready(function() {
            function callNodeJs() {
                    $.ajax({
                            // setup the server address
                            url : 'http://judyhost:8000',
                            success : function(response, code, xhr) {
                                // on success
                                $('#updateId').append(response + "</br>");
                                    callNodeJs();
                            },
                            error : function() {
                              // on error
                              alert("error");
                            }
                    });
            };
    
            callNodeJs();
    });
    
This example is obviously very simple, but can easily be modified to watch for ANY event to happen and solved in the same fashion.

2 comments:

  1. Thanks for this post Judy. I'm just getting into Node.js myself so this gives me great info to learn from.

    Jeff Hendrickson

    ReplyDelete

I appreciate your time in leaving a comment!