Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Node.js: Best practices for the JavaScript server side framework

See in this article the main goals of Node.js technology, its use cases, best ways to use, and much more.

Node.js is divided into two parts. It is partially a runtime environment and partially a library which is used for building network based applications using the server-side JavaScript. Internally this makes use of the Chrome's JavaScript based runtime engine in order to execute the JS code directly without interacting with the browser's sandbox.

In this article I will explain how to use node.js. Before we go into further details we must understand that Node is not any sort of web server. It doesn't come with any ability to carry on task on its own. We should understand the fact that, It doesn't work like Apache. In Node.js, we do not have any configuration file which we can point to our HTML files. If you want to use Node.js as an HTTP server, we need to develop an HTTP server with the help of the available standard libraries. Let me make this point very clear that Node.js is just another way to execute a piece of code on the computer. It is simply a JavaScript runtime.

JavaScript vs. Node.JS

So far we know that JavaScript runs on the browser. Node.JS is an enhanced version of JavaScript which runs on server. In short, Node.js is JavaScript on server, let us think of a problem: Since JavaScript really has two or three lives, the major part is the funny little DHTML helper which evolved around the mid-90's, the more serious frontend development stuffs e.g. jQuery and the other similar tools and of course the recent server-side components. It is not an easy task to find any study material which can help anyone to learn JavaScript in the correct way. This is very important in order to write Node.js applications in a mechanism that makes one feel that he/she is not just using JavaScript; he/she is actually developing it.

Goal of Node.js

The goal of Node.js is to provide a mechanism which will allow building a scalable network programs in an easy manner.

Advantages of Using Node.js

Node.js comes with three features:


  • Easy to use
  • Fast
  • Scalable

In Node.js, a little amount of code does a lot of work. Its concurrency model is simpler compared to the traditional thread programming. Similar to popular client side java script libraries, node.js has abstraction to most of the complex under cover functionalities. It is very effective for beginners as they do not need to go into the micro level implementation. The other aspect of node.js is its efficient memory management under high volume and non-blocking execution mechanism. Node.js also has a different mechanism for I/O; its functions never perform any direct I/O so the processing is fast and non-blocking. As a result, dead lock situation never arises and the developers can concentrate on coding only. So node.js is very popular in developer community for fast network based application development.

Installing and setting up Node.JS

Node.js can be downloaded from the website - https://nodejs.org/download/. Download the exact installable as per your environment and run it. Let us assume that we are on a 64 bit windows box and hence our installable would be downloaded from - https://nodejs.org/dist/v0.12.7/x64/node.exe. Once downloaded move this exe file into a folder e.g. D:\NodeJS and then simply run it by typing node.exe from your command prompt as shown below -

Figure 1 - Run the node.exe from command prompt.

Let us use this following code snippet which illustrates how simple and easy it is to write a simple server. It listens on port 8090 and responds to requests with a welcome message:

Listing 1: A simple node js example code

  var http = require( "http" );
  http.createServer( function( request, response ) {  
    response.writeHead( 200, { "Content-Type": "text/plain" });  
    response.write( "Welcome to the Node.js server!" );  
    response.end();
  }).listen(8090);
  console.log( 'Server is listening on http://localhost/ on port 8090…' ); 

Run this code on your command prompt as shown below:

Figure 2 - Run the node.exe ex1.js from command prompt

You should get the following output -

Listing 2 - Output on the command prompt

  Server is listening on http://localhost/ on port 8090?
  


Now open a browser and type in the following URL -

Listing 3 - Browser URL

  http://localhost:8090/
  

Figure 3 - Output on the browser - Welcome to the Node.js server!


We see that in the above code, first, we need to call to a function called require(). The use of require() is the core to use the modular JavaScript, and something of which Node takes heavy advantage. Here, the resulting http variable is used to create the server. This server is then handed with a new function block to run when it is contacted. This function is a simple function which ignores the request completely and simply writes out a response, in text/plain format - “Welcome to the Node.js server!”.

The above code can be divided into following steps -


  • Step 1 - The first step is to define the type of interaction and get a variable that will work along with this interaction using the require() function.
  • Step 2 - The second step is to create a new server using the method - createServer ().
  • Step 3 - In the third step we write a function within that server which will be handling the requests. This request handling function should include a request …… and a response.
  • Step 4 - Finally in step 4 we tell the server to start the handling requests on a specific port and IP using the listen function.

Let us enhance the above example as under -

Listing 4: modified the simple node js example code

  var http = require("http"), 
         url = require("url"); 
   
  http.createServer(function (request, response) { 
         request.on('end', function () { 
               var _get = url.parse(request.url, true).query; 
               // Write headers to the response. 
               response.writeHead(200, {'Content-Type': 'text/plain' }); 
               // Send data and end response. 
               response.write('Here is the data: ' + _get['data']); 
               response.end();
         }); 
  // Listen on the 8090 port. 
  }).listen(8090); 
  

If we execute this by saying node.exe ex2.js, and provide some data in the URL e.g. "http://localhost:8090/?data=Hello, I am from browser", it will show the message on the console.

Let us see an example where we can connect to MySQL database. To achieve this, let us assume that we have a mysql database on the same box where we are running Node.JS

Listing 5: Simple node js example code to connect MySQL database

  var http = require('http'), 
      mysql = require("mysql"); 
          
  var connection = mysql.createConnection ( { 
         user: "root", 
         password: "r00t123", 
         database: "my_db_local"
  } ); 
   
  http.createServer ( function ( request, response ) { 
         request.on ( 'end', function () { 
         connection.query ( 'SELECT * FROM my_created_table;', function ( error, rows, fields ) { 
               response.writeHead( 200, { 'Content-Type': 'x-application/json' }); 
               response.end( JSON.stringify(rows) ); 
               }); 
         }); 
  // Listen on the 8090 port. 
  }) .listen(8090);
  

Querying the database using the Node.js library is quite easy. We simply need to enter the query string and the callback function. In a real time application, we need to check if there are any errors. If there is any error, the error parameter will not be undefined. It then sends response codes depending upon the success or the failure of the query. It should also be noted here that we have set the Content-Type to x-application/json, which is a valid MIME type used in case of JSON. The rows variable contains the result of the query, and we simply need to convert the data in rows to a JSON string with the help of JSON.stringify() method. If we execute this on a browser, we would be prompted to download the data in a JSON format.

How Node.JS works?

The main idea of Node.js: is to use the non-blocking, event-driven Input / Output so that it remains lightweight and efficient on top of the data-intensive real-time applications that are used to run across distributed devices. Thus, Node.js is not another new platform or framework which is going to dominate the web development arena. Rather, it is a simple platform which is made to meet a particular need. It is absolutely essential to understand it in full length before jumping into any development. Any developer would definitely not use Node.js for operations that are CPU - intensive. Actually, for heavier computations, node.js will stop all its advantages. Node.js shines in an environment where fast, scalable network based applications are required. It is very interesting part to learn how the whole things work. As compared to the traditional web serving mechanism where each and every connection or request starts a new thread thus, taking up the available RAM on the system. Eventually the RAM gets MAX out i.e. there is no more memory available on the computer to run other programs which leads to a system crash and also blocks the basic I/O operations.

Conclusion

Through this document, I have tried and covered the different corners of Node.JS. Also I have talked how to do the initial set up and execute some sample code. Let us summarize our discussion in the form of following bullets -


  • Node.js is partially a runtime environment and partially a library which is used for building network based applications.
  • Node.js is the server side counterpart of Javascript.
  • Every call in Node.JS is asynchronous.
  • To develop a Node.js based application, we might need some extra effort but it worth when we see the benefit of getting a robust, fast application.
  • Node.js is a promising technology and is an excellent choice in order to develop an application which is heavily loaded.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login