Wednesday, January 8, 2014

Beginner’s Guide To Node.Js (Server-Side JavaScript)

By Filed in Web Design
Node.js – in simple words – is server-side JavaScript. It has been getting a lot of buzz these days. If you’ve heard of it or you’re interested in learning and getting some hands on it – this post is for you.
node.js
(Image Source: node.js)
So what exactly is the need of using JavaScript in the server? To make the concept of Node.js clear I would like to compare it with the ordinary server-side languages such as PHP. Node.js uses anevent-based server execution procedure rather than the multithreaded execution in PHP.
To explain it further, we’ll be talking about the idea of what Node.js is along with some hosting provider suggestions and installation tips. Intermediate level knowledge of JavaScript, jQuery and Ajax are required, but we’ll also provide examples for you to understand the entire thing easier and even work on it, so let’s get to know more about Node.js!

Let’s Consider A Case:

Consider a website in which you need to load content dynamically from another web server which is slow. In PHP you can do it in 2 ways – coding it in a simple file and coding it as another script, then executing it in a multithreaded approach.
multi threaded execution
In the first method even though the code is simple the execution pauses for a while at the point where the slow web server is accessed. The second method is more optimized in case of performance but it’s hard to code and it has a multithread management overhead. The case is similar for most of the web programming languages other than the server-side JavaScript, i.e., Node.js.
What’s the difference in Node.js? In order to understand Node.js you must keep in mind theJavaScript’s event based programming in the browser. We utilize the same technology here. Instead of using a separate thread, a function is attached to the finish event of the “slow web server access” mentioned above, thus you get the full functionality in the optimized second option mentioned above without any multithread overhead.

Getting Started With Node.Js

Node.js is JavaScript. Why can’t we utilize the event based functionality of JavaScript in the client to a server? This thought might have led to the development of Node.js.
event based execution
That said, the main highlight of Node.js – it is event-based asynchronous functions. It uses anevent loop instead of waiting for I/O operations (accessing external web service, accessing hardware).
Node.js could still make use of its processing power when the server is waiting for any other operation. This makes Node.js scalable to millions of concurrent connections.

How Does JavaScript Run On A Server?

Node.js works on a v8 environment – it is a virtual machine or a JavaScript engine that runs the JavaScript code, so for hosting you can’t use the ordinary web hosts. You will need the ones that have the v8 environment.
Here are some provider suggestions for Node.js hosting:
  1. bejes.us
  2. Cloud Foundry
  3. Cloudnode
  4. DotCloud
  5. Duostack

Installing Node.Js

Node will work perfectly on Linux, Macintosh, and Solaris operating systems. On Windows you can install it using the Cygwin emulation layer. None of the builds in Windows are satisfactory but it is still possible to get something running.
Option 1: Building Node from source.
Use make to build and install node.js (execute the following on the command line). Git is required.
  1. git clone --depth 1 git://github.com/joyent/node.git  
  2. cd node  
  3. git checkout v0.4.11  
  4. export "http://www.hongkiat.com/blog/out/freelancer" style="" target="_blank" rel="nofollow" onmouseover="self.status='http://www.hongkiat.com/blog/out/freelancer';return true;" onmouseout="self.status=''">JOBS=2  
  5. mkdir ~/local  
  6. ./configure --prefix=$HOME/local/node  
  7. make  
  8. make install  
  9. echo 'export PATH=$HOME/local/node/bin:$PATH' >> ~/.profile  
  10. echo 'export NODE_PATH=$HOME/local/node:$HOME/local/node/lib/node_modules' >> ~/.profile  
  11. source ~/.profile  
Option 2: Installing Node.js from Package
For Mac users, you can install Node.js as a package fromhttps://sites.google.com/site/nodejsmacosx/ which is pretty self-explanatory.

Testing Node Installation

In order to check your successful Node installation we can try out a very simple console "Hello World" program. Create a file named "test.js" and write the following code into it.
  1. var sys = require("sys");  
  2. sys.puts("Hello World");  
Code explanation:
It loads the sys class into a variable sys. It then uses the sys object to perform the console tasks. The sys.puts is a command similar to the cout in C++, so in order to run the script above go to the command prompt and run it by the command below:
  1. node test.js  
If your installation is successful then you will get a hello world output in the screen.
hello world

Creating A HTTP Server

Now it’s time to create a "Hello World" via web server using Node.js. Here’s what we are going to do – we create a server that outputs a “Hello World” to the localhost on the port 8080 no matter what the URL is, giving you an idea what event is.
The codes:
  1. var sys = require("sys"),  
  2. my_http = require("http");  
  3. my_http.createServer(function(request,response){  
  4.     sys.puts("I got kicked");  
  5.     response.writeHeader(200, {"Content-Type""text/plain"});  
  6.     response.write("Hello World");  
  7.     response.end();  
  8. }).listen(8080);  
  9. sys.puts("Server Running on 8080");   
Code explanation:
The most interesting part in Node.js is its event-based programming. In order to create a HTTP server we need the HTTP library, so we go forward and add it using my_http. We create server by the function:
  1. my_http.createServer(function(request,response){}).listen(8080);  
The function given as the first argument is executed every time an event is triggered in port 8080, so the function itself suggests the node to listen for an event in port 8080. In order to detect this, I have added a “I got kicked” message which will be displayed on the console screen whenever a request is received.
The request object contains all the information about the request that has been made to the server. For example it contains the URL string. The response object is the object that handles the response from the server. First we set the header of the response as a text/plain content, then outputs “Hello World“, then end the output stream. 200 is the status response.
Well, the above one is a very simple example but we can see that whatever URL we give in the browser for the same server we get the same output like “Hello World”.

Creating Simple Static File Server

Let’s create a simple static file server in the next tutorial.
The codes:
  1. var sys = require("sys"),  
  2. my_http = require("http"),  
  3. path = require("path"),  
  4. url = require("url"),  
  5. filesys = require("fs");  
  6. my_http.createServer(function(request,response){  
  7.     var my_path = url.parse(request.url).pathname;  
  8.     var full_path = path.join(process.cwd(),my_path);  
  9.     path.exists(full_path,function(exists){  
  10.         if(!exists){  
  11.             response.writeHeader(404, {"Content-Type""text/plain"});    
  12.             response.write("404 Not Found\n");    
  13.             response.end();  
  14.         }  
  15.         else{  
  16.             filesys.readFile(full_path, "binary"function(err, file) {    
  17.                  if(err) {    
  18.                      response.writeHeader(500, {"Content-Type""text/plain"});    
  19.                      response.write(err + "\n");    
  20.                      response.end();    
  21.                  
  22.                  }    
  23.                  else{  
  24.                     response.writeHeader(200);    
  25.                     response.write(file, "binary");    
  26.                     response.end();  
  27.                 }  
  28.                        
  29.             });  
  30.         }  
  31.     });  
  32. }).listen(8080);  
  33. sys.puts("Server Running on 8080");           
Codes explanation:
The above code is pretty simple, we will discuss it as blocks.
  1. var sys = require("sys"),  
  2. my_http = require("http"),  
  3. path = require("path"),  
  4. url = require("url"),  
  5. filesys = require("fs");  
All these libraries are required for the program. Its usage will be clear in the following code.
  1. var my_path = url.parse(request.url).pathname;  
  2. var full_path = path.join(process.cwd(),my_path);  
The request object has the request details as we have discussed earlier. We use the parsefunction of the URL class which we have included to get the pathname of the request URL. After getting the pathname we concatenate it with the path of the current working directory in order to get the full path of the file.
For joining URLs we have a function called join in the path library.
  1. path.exists(full_path,function(exists){  
After getting the full path we check whether the path exists by the function exists. After the check is done the callback function is called and passed as the second argument.
  1. if(!exists){  
  2.     response.writeHeader(404, {"Content-Type""text/plain"});    
  3.     response.write("404 Not Found\n");    
  4.     response.end();  
  5. }  
  6. else{  
  7.     filesys.readFile(full_path, "binary"function(err, file) {    
  8.          if(err) {    
  9.              response.writeHeader(500, {"Content-Type""text/plain"});    
  10.              response.write(err + "\n");    
  11.              response.end();    
  12.          
  13.          }    
  14.          else{  
  15.             response.writeHeader(200);    
  16.             response.write(file, "binary");    
  17.             response.end();  
  18.         }  
  19.                
  20.     });  
  21. }  
Now in the callback function if the file does not exist we send a "404 Page Not Found" error.
If the page is found then we read the file by the readFile function in file system. We can also see the callback function for the readFile function defined there itself. If there is no error in reading the file then it will be displayed. If there is an error then a status 500 is returned with the error text.
I also recommend wrapping codes of the previous tutorial into a function so that you can use it in the next tutorial or for future use.
  1. var sys = require("sys"),  
  2. my_http = require("http"),  
  3. path = require("path"),  
  4. url = require("url"),  
  5. filesys = require("fs");  
  6. my_http.createServer(function(request,response){  
  7.     var my_path = url.parse(request.url).pathname;  
  8.     var full_path = path.join(process.cwd(),my_path);  
  9.     path.exists(full_path,function(exists){  
  10.         if(!exists){  
  11.             response.writeHeader(404, {"Content-Type""text/plain"});    
  12.             response.write("404 Not Found\n");    
  13.             response.end();  
  14.         }  
  15.         else{  
  16.             filesys.readFile(full_path, "binary"function(err, file) {    
  17.                  if(err) {    
  18.                      response.writeHeader(500, {"Content-Type""text/plain"});    
  19.                      response.write(err + "\n");    
  20.                      response.end();    
  21.                  
  22.                  }    
  23.                  else{  
  24.                     response.writeHeader(200);    
  25.                     response.write(file, "binary");    
  26.                     response.end();  
  27.                 }  
  28.                        
  29.             });  
  30.         }  
  31.     });  
  32. }  
  33. my_http.createServer(function(request,response){  
  34.     var my_path = url.parse(request.url).pathname;  
  35.     load_file(my_path,response);  
  36. }).listen(8080);  
  37. sys.puts("Server Running on 8080");           

Stay Tuned !

That’s all. Hope this gives you a good idea of Node.js. In the next article, I’ll be showing you how toload and display number of Facebook likes using Node.js. Stay tuned!

4 comments:

oakleyses said...

louis vuitton handbags, oakley sunglasses, louboutin, longchamp outlet, nike shoes, louis vuitton outlet stores, chanel handbags, burberry outlet, prada outlet, jordan shoes, tiffany and co, michael kors outlet, tory burch outlet, louis vuitton outlet, longchamp handbags, nike free, true religion jeans, michael kors outlet, kate spade outlet, polo ralph lauren outlet, tiffany and co, prada handbags, polo ralph lauren outlet, michael kors outlet, michael kors outlet, longchamp handbags, oakley sunglasses, ray ban sunglasses, kate spade handbags, burberry outlet, louis vuitton outlet, louboutin outlet, louboutin, coach factory outlet, air max, air max, coach outlet, gucci outlet, christian louboutin shoes, michael kors outlet, coach purses, ray ban sunglasses, michael kors outlet, louis vuitton, coach outlet store online, true religion jeans, oakley sunglasses cheap

oakleyses said...

ralph lauren, lululemon, air max, hollister, north face, nike air max, polo lacoste, vanessa bruno, timberland, vans pas cher, louboutin, louis vuitton, oakley pas cher, air max pas cher, nike roshe run, air max, true religion outlet, barbour, sac longchamp, air force, hollister, sac louis vuitton, nike free, polo ralph lauren, nike trainers, louis vuitton uk, nike roshe, sac hermes, longchamp, michael kors, sac burberry, sac guess, mulberry, new balance pas cher, converse pas cher, sac louis vuitton, hogan outlet, nike tn, north face, true religion outlet, ray ban pas cher, michael kors, air jordan, nike blazer, nike free pas cher, michael kors pas cher, abercrombie and fitch, ray ban sunglasses

oakleyses said...

mac cosmetics, mont blanc, marc jacobs, canada goose outlet, nike huarache, vans shoes, soccer jerseys, hollister, giuseppe zanotti, beats by dre, abercrombie and fitch, longchamp, insanity workout, celine handbags, bottega veneta, ghd, nfl jerseys, north face outlet, chi flat iron, ugg boots, birkin bag, ugg australia, canada goose, herve leger, ugg pas cher, rolex watches, valentino shoes, canada goose uk, canada goose, ferragamo shoes, canada goose, ugg boots, uggs outlet, north face jackets, soccer shoes, asics running shoes, new balance shoes, p90x, lululemon outlet, canada goose jackets, mcm handbags, instyler, babyliss pro, ugg, wedding dresses, jimmy choo outlet, reebok outlet, nike roshe run

oakleyses said...

parajumpers, karen millen, air max, converse, pandora charms, moncler, louboutin, moncler, links of london, lancel, juicy couture outlet, oakley, hollister, pandora charms, supra shoes, thomas sabo, canada goose, gucci, wedding dresses, timberland boots, swarovski crystal, air max, coach outlet store online, moncler, ray ban, canada goose, moncler, ugg, louis vuitton, swarovski, hollister, montre homme, moncler, hollister clothing store, ralph lauren, rolex watches, moncler outlet, moncler, iphone 6 cases, baseball bats, juicy couture outlet, toms shoes, vans, pandora jewelry, ugg, converse shoes