Search This Blog

Tuesday, November 26, 2013

Beginner’s Guide to Node.js (Server-side JavaScript)

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.

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.

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.

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.

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.

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:

node test.js

If your installation is successful then you will get a hello world output in the screen.

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 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:

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”.

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.

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.