Posted by on Aug 12, 2013 in Blog

It is a web server built on the open source V8 JavaScript engine from Google, which allow you to right server side JavaScript if you require more information please visit the Node.js website.

Node.js is only an environment – meaning that you have to do everything yourself. There is not a default HTTP server, or any server for that matter. This can be overwhelming for new users, but the payoff is a high performing web app.

Our objective from this quick tutorial is to break the ice between the developers and new interesting server-side platform Node.js.

Downloading & Installing

You download the installer file from this link http://www.node.js/org

After running the installer file you should find Node.js files in “Programs Files/nodejs” folder, which contain all the required files and libraries to starting building your first project.

Creating new project

  1. Create a new main.js file using any text editor and save it in your main project folder.
  2. At the start of main.js you will start by defining objects  required. The Node.js instruction to do this is “require” as show in the code below.
    var http = require('http'); // for creating the HTTP server
    var querystring = require('querystring');  // for parsing the POST submitted data of the form
    var mysql  = require('mysql'); // for MySQL database connection
  3. You have to use the http instance to create the HTTP server and make it listen to the desired port, in my below example I made listen to 8080 port.
     http.createServer(function (req, res) { 
    // code ……
  4. In my example I need to URLs one that serve the form and a second one to process the form data after submit in this case I used a “switch” statement to branch the code inside http.createServer function as below.
    http.createServer(function (req, res) {     
     switch(req.url) {      
     case '/':     
     /// the code to server the form should be here         
     case '/formhandler': 
     /// the code to process the sumbited data should be here      break;    
     // default response from  server if any undefined URL is requested
    res.writeHead(404, "Not found", {'Content-Type': 'text/html'}); 
    res.end('<html><head><title>404 - Not found</title></head><body><h1>Not found.</h1></body></html>');        
     console.log("[404] " + req.method + " to " + req.url);     
     }; //end switch 
  5. In the part of the code that server the form you have to use res.writeHead() method to set the response header and res.wirte() method to send HTML in the output buffer of the response as below.
    res.writeHead(200, "OK", {'Content-Type': 'text/html'});
    res.write('<html><head><title>Form - Test</title></head><body>');
    res.write('<center><h1>Welcome , who are you?</h1><br/>');
    res.write('<form  action="/formhandler" method="post" class="validForm1">');
    res.write('Name: <input type="text" name="name" value="" /><br /><br/>');
    res.write('Age: <input type="text" name="age" value=""/><br /><br/>');
    res.write('Phone: <input type="text" name="phone" value=""/><br /><br/>');
    res.write('<input type="submit" value="Submit"/>');
  6. The second part of the code where you should receive and process the POST data submit by form, the first thing to do is combining the post data that will come in chunks in one variable and require the use of the event.
    var fullBody = '';
    req.on('data', function(chunk) { fullBody += chunk.toString(); });
  7. Saving the posted data in database should happen after server receive all the data chunks and the only way to do this is to make our code listen the request end event as below.
    req.on('end', function() {
    var decodedBody = querystring.parse(fullBody);
    // the code to connect to MySQL database
    // and save data should be here
    res.writeHead(200, "OK", {'Content-Type': 'text/html'});

    In the above code notice the use of querystring.parse() method to process the submitted data, which will return a JSON object with the form fields names.

  8. Connection to MySQL should happen using the mysql module as below code shows.
    var connection = mysql.createConnection({
    host: "localhost",
    user: "DB_USERNAME",
    password: "DB_PASSWORD",
    database: "DB_DATABASE_NAME"

    Note: MySQL database doesn’t come with Node.js installer you need to run a version of it on your machine like the one comes with WAMP server.

  9. Saving the data to database is done using the connection object and query method as below.
    connection.query("insert into user_data(name,age,phone) values('"+
    function (error, rows, fields) {

    in the above code you can detect the status of SQL execution inside the callback function in connection.query() method. Also “addslahses()” function is not a native Node.js function, I worte this function to help with stiring process before inserting in database.

    function addslashes(str){
    str = str.replace(/\\/g,'\\\\');
    str = str.replace(/\'/g,'\\\'');
    str = str.replace(/\"/g,'\\"');
    str = str.replace(/\0/g,'\\0');
    return str;

Running the Node.js Server

To run the HTTP serve that comes with Node.js you have to execute the below using command line cocole while your current directory is the project folder.

node main.js

After running the above command your ready to check the project by typing http://localhost:8080/ in your web browser, if everything is correct you should see a page with the form.

To stop the HTTP server you can use CTRL+C on your keyboard.

Any change you need to make to the project files you have to stop the HTTP server and run it again with the instructions above.

Final word

Node.js is a very powerful platform but it is more suitable for building online web services and APIs.

To download the full example code click here, and you are invited to share your feedback and comments using the form below.

Like how we think? Lets Collaborate!