Apr
6
2016

An Introduction to Node.js

node.js

Node.js is a buzzword in the software development industry and it has become a trend to develop enterprise level applications using Node. Some of the big companies are already converting their applications to Node.js now. Therefore it seems high time to start looking in to Node.js.

 

What is Node.js

Node.js

Node.js is an open source JavaScript runtime environment for developing server-side networking applications using JavaScript. It was developed by Ryan Dahl in 2009. It uses Google Chrome V8 JavaScript engine as the interpreter and libuv as the abstraction layer. Core libraries in Node.js itself are written in JavaScript. There is are a huge number of packages available to use in Node.js with Node Package Manager (NPM). Node.js supports cross platforms, and can be deployed on Windows, Linux and OS X.

Node.js is very fast and highly scalable, due to its event driven and non-blocking I\O model. This enables to develop high throughput, real-time network applications with Node.js.

It has an asynchronous, non-blocking, programming model for lightning-fast speed and enables the use of JavaScript on the server-side so that both client and server run using the same language.

Until recently, highly concurrent programs were limited to network programmers but now any web developer with JavaScript skills can write the same kind of highly-scalable programs quickly and easily with Node.js. It changes the notion of how a server should work. Its goal is to enable a programmer to build highly-scalable applications and write code that handles tens or even hundreds of thousands of simultaneous connections on just one server. Unlike jQuery, YUI, MooTools, Node.Js is a server side Javascript framework which will allow you to perform any operation that can be done by other server side languages like PHP, Java or Dot Net.

How Node.js works – Single Threaded model with Event Loop architecture

How Node.js works

The heart of Node.js processing model is “Event Loop”. Node JS platform does NOT follow Request/Response Multi-Threaded Stateless Model. It follows Single Threaded and Event Loop Model. Node.js Processing model mainly based on Java Script Event based model with Java Script Callback mechanism.

As Node.js follows this architecture, it can handle more and more concurrent client requests very easily. And also because of the event loop, even though our Node.js application receives more and more concurrent client requests there’s no need to create more and more threads. Further Node.js application utilize only less resources or memory since it uses less threads.

Why Node.js stands out among other technologies

Why should this make the switch away from tried-and-tested platforms such as Ruby, PHP, Python or .NET for a fresh technology? Points to consider are as follows.

  1. End-to-end Javascript
  2. Scalability
  3. To be ready for the next generation of real-time web applications
  4. Performance
  5. Maximising use of hardware resources
  6. Thriving community
  7. Finding developers
  8. Keeping your development team happy
  9. Faster development time and great productivity gains
  10. Enterprise hosting options

When to Use Node.js

  • Chat programs
  • API on top of an object DB (Ex: MongoDB)
  • Queued inputs
  • Data streaming
  • Proxy
  • Application or system monitoring dashboards
  • Server side web applications

When Not to Use Node.js

  • Heavy server-side computation / processing
  • Server-side web application with relational DB

How to install

Node.js installation is simple. Download the installer from the Node.js web site and double click to install it. This is for Windows users, and for other OS users, installation is same as any other installation.

Bring up command prompt and type ‘node –version’ which will output the installed version of the Node.js. Now you can install the required package using NPM. In the command prompt type ‘npm install learnyounode’. This will install the package in the current folder location. This a tutorial.

IDE and tools

There are many IDE’s available that provide rich and easy to use IDE. In addition, the community edition of the VS2015 is free. Adding Node.js Tools for Visual Studio provides a variety of features for node.js development. This tool is free and open source. This will also provide project templates to create common types of Node applications. Eclipse, WebMatrix and support for Node.js development. It is not essential to have IDE to develop node applications, but using an IDE makes it much easier. Remember you can always develop application with just using a notepad.

Among the common IDE’s Visual Studio is one of most feature Sublime Text are some other IDEs that can be used for Node.js development.

Tutorials

There are many tutorials available for learning node.js but using learnyounode is recommended. Tutorial itself is a NPM package. This is recommended because it is interactive and well arranged. It will provide you with challenge to fulfil writing small node applications and verify whether you have done it correctly. It will provide you with some hints on how to do it and what functions or packages to use. This is entry level to node.js tutorial and assumes you know JavaScript. If it is not the case, there are courses for learning JavaScript or more advanced node topics. And this is also free and open source.

Sample demo – A basic chat application

  1. Download and install Node.js.
  2. Create a new directory for your chat project and inside that directory, create two new files named main.js which will be our server, and client.html which will be our client.
  3. Load the relevant modules coming with node.js. To load a module you need to use the require function. Using http module we can create a server as mentioned below, which handles and answers all http requests coming from the clients, and in this case, sending the client.html file contents back to the user.
    var http = require('http');
    var app = http.createServer(function (request, response) {
    …
    …
    
    }).listen(1000);

    To read the contents of a file from the file system, we need to use fs module in node.js.

    var fs = require('fs');
  4. Creating the server: Inside the http.createServer function, needs to include the below codes.
    var app = http.createServer(function (request, response) {
        fs.readFile("client.html", 'utf-8', function (error, data) {
            // Begin the responses
    	 response.writeHead(200, {'content-type': 'text/html'});
    
            // Send the contents of client to the user
    	 response.writeHead(data);
    	 response.end();
        });
    
    }).listen((<port>); // Start the server using listen() method with port number.
  5.  Install socket.iomodule for sending/receiving messages. Open a Node.js terminal, go to our project directory, and install socket.io using the below command.
    npm install socket.io
  6. Then use socket.io module to send the data back and forth.
    var io = require('socket.io').listen(app);
  7. Setting up our Event, to be fired by the client, and the server will respond to,
    io.sockets.on('connection', function(socket) {
        	socket.on('message_to_server', function(data) {
            	io.sockets.emit("message_to_client", { message: data["message"] });
        	});
       });
  8. Creating our client html: This is a basic html page. And we need to include the socket.ioclient-side library for message processing.
    <!DOCTYPE html>
    <html>
    <head>
        <title>Chat demo</title>
        <script src="/socket.io/socket.io.js"></script>
        <script type="text/javascript">
    	// Our message processing scripts
    	..
    ..
        </script>
    </head>
    <body>
        <input type="text" id="txtMessage" />
        <button onclick="sendMessage()">Send</button>
        <br />
        <br />
        <div id="divChatlog"></div>
    </body>
    </html>
  9. Chat message processing scripts.
    <script type="text/javascript">
            // Socket connection
            var socketio = io.connect("127.0.0.1:1000");
    
            // Send message to server & then to the other connected clients
            function sendMessage() {
                var msg = document.getElementById("txtMessage").value;
                socketio.emit("message_to_server", { message: msg });
            }
    
            // Receive message & display
            socketio.on("message_to_client", function (data) {
                document.getElementById("divChatlog").innerHTML = ("<hr/>" +
       data['message'] + document.getElementById("divChatlog").innerHTML);
            });
        </script>
  10. Run the chat server. Open a Node.js terminal, go to our project directory and type the below command.
    node main.js
  11. Sending chat messages: Open our chat client in any browser by typing in the IP and the port (Ex: 127.0.0.1:1000). You should see all the messages you send appear in the ‘div’ below the input text box. And the exciting part is you’ll also see the messages from other people send when they use the page as well. For that, open another browser or tab & try sending messages.

References:

 

Authors: Shan Perera and Dilushi Fernando

Leave a comment

*