Thursday 12 March 2015

Node.js : allowing you to execute JavaScript code in Backend context (outside web browsers)

A very good description of Node.js is shown on that web site : http://www.nodebeginner.org/ (or http://nodejs.developpez.com/tutoriels/javascript/node-js-livre-debutant for the french equivalent).

What is Node.js ?... it's a server-side JavaScript

The first incarnations of JavaScript lived in browsers (on frontend with DHTML first, then, more recently, with frameworks like jQuery). But this is just the context. It defines what you can do with the language, but it doesn't say much about what the language itself can do. JavaScript is a "complete" language: you can use it in many contexts and achieve everything with it you can achieve with any other "complete" language.

Node.js really is just another context: it allows you to run JavaScript code in the backend, outside a browser.

In order to execute the JavaScript you intend to run in the backend, it needs to be interpreted and, well, executed. This is what Node.js does, by making use of Google's V8 VM, the same runtime environment for JavaScript that Google Chrome uses.

Plus, Node.js ships with a lot of useful modules, so you don't have to write everything from scratch, like for example something that outputs a string on the console.

Thus, Node.js is really two things: a runtime environment and a library.

You will find the official installation instruction on that side: https://github.com/joyent/node/wiki/Installation. (I will take here the MS Windows version)


The "hello world" example code using Node.js as a simple web-server

Once, you have downloaded and executed the installation, the first thing that I will suggest is to create a folder ; let's call it "node" ; in that folder, you will put your JavaScript scripts.

let's  create a new file server.js in that folder and paste the following code in that file :

var http = require("http");

http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}).listen(8080);

If this port is already used, you just have to change it!

All you need now, it's to launch the "Node.js command prompt" and type : 'node node\server.js' and press the Enter key.

Then, go and type on a web browser the following URL : http://localhost:8080/

You should see the following display on the web page : "Hello World"

Creating our Node.js server module

It's common to have a main file called index.js which is used to start our application ;
We will show about how to make server.js a real Node.js module that can be used by our yet-to-be-written index.js main file.
About our server.js, we don't have to change that much. Making some code a module means we need to export those parts of its functionality that we want to provide to scripts that require our module.

For now, the functionality our HTTP server needs to export is simple: scripts requiring our server module simply need to start the server.

To make this possible, we will put our server code into a function named start, and we will export this function:

server.js
var http = require("http");
var url = require("url");

exports.start = function () {
  function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received.");
    console.log("Request received.");
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    response.end();
  }
  http.createServer(onRequest).listen(8080);
  console.log("Server has started.");
};

Notice, here above, that we added a new module module (url) to track the path name of the URL (request); 
This way, we can now create our main file index.js, and start our HTTP there, although the code for the server is still in our server.js file.

Create a file index.js with the following content:

index.js
var server = require("./server");
server.start();

As you can see, we can use our server module just like any internal module: by requiring its file and assigning it to a variable, its exported functions become available to us.
That's it. We can now start our app via our main script, and it still does exactly the same:

node index.js

(Note that our server will probably write "Request received." to STDOUT two times upon opening the page in a browser. That's because most browsers will try to load the favicon by requesting http://localhost:8888/favicon.ico whenever you open http://localhost:8888/).

Accessing MySQL Databases

"Most traditional server-side technologies have a built-in means of connecting to and querying a database. With Node.js, you have to install a library. For this tutorial, I've picked the stable and easy to use node-mysql. The full name of this module is mysql@2.0.0-alpha2 (everything after the @ is the version number). Open your console, navigate to the directory where you've stored your scripts, and execute the following command:  npm install mysql@2.0.0-alpha2

This downloads and installs the module, and it also creates the node_modules folder in the current directory. " (cf. http://code.tutsplus.com/tutorials/nodejs-for-beginners--net-26314)
Now let's look at how we can use this module to export  json  results from a sql query ;  here, is an example :
var mysql      = require('mysql');
var psn_id = 376257924;

var connection = mysql.createConnection({
  host     : 'host_name',
  user     : 'user_name',
  password : 'password',
  database : 'db_name',
});
var queryString = "SELECT * FROM your_table WHERE id = ? " ;
var http      = require('http');
var rep = "";
connection.query(queryString, psn_id, function (error, rows, fields) { 
// Rows variable holds the result of the query. 
rep = JSON.stringify(rows); 
}); 
// Create the http server. 
http.createServer(function (request, response) { 
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write(rep);
  response.end();
// Listen on the 8080 port. 

}).listen(8080);