Node.js is a framework/runtime environment for Javascript .It is open source and is built using the Chrome’s V8 Javascript engine which supports ECMAscript.
Traditionally javascript is used for writing scripts for the browser.But Node.js makes it possible to use javascript for server side applications.
When we think about Javascript we usually think about it as a scripting language that executes in a web browser.And this infact is the most common use of javascript.JavaScript is understood by almost all the browsers.This makes javascript one of the most widely used languages in the world.
But Node.js provides a runtime environment which allows execution of javascript outside the browser.
V8 , the JavaScript engine used by Node.js performs just in time compilation of the JavaScript code rather than interpreting the code.The code is compiled to native machine code at runtime.This gives a big performance boost to the application.
Unlike traditional applications in which there is a separation between the web server and the application logic ,a Node.js application in contrast is the same as the web server.Node.js provides an HTTP module which serves the request and can be used in a Node.js application.
Traditional Web Application
Node.js application
Node provides several advantages over other server side programming frameworks
- In web servers such as Apache a thread is created for every request received by the web server.If there are lots of concurrent requests this means that a lot of threads will be created.As every thread consumes resources hence having a lot of threads on the server can degrade the server performance.
Node uses only a single thread so the overhead of creating a new thread for every request is not there. - In a normal web application when any operation is required to be done such as doing some computation or executing a database query the program execution blocks.When the
operation completes the program continues execution.In contrast in a Node application when any operation is required to be done then instead of blocking ,the program execution continues.When the operation completes ,a callback is called which receives the result of the operation. - The advantage of this asynchronous model is that program execution is not blocked and server is able to handle lots of concurrent requests.
- Node.js allows to use the same language ,javascript across the browser and server.This allows to reuse the same code such as validation code both on the browser and the server.Not only this Javascript is also used in various NoSQL databases such as MongoDB.
- There are lot of third party modules available for building an application in node.js
Node.js is more suitable for applications which require real time functionality.Examples of such type of applications are Chat application,Reservation systems.This is because Node.js can support I/O operations over multiple concurrent connections.
Its can be used not just for server side programming but can also be used for developing different types of application.Some of the useful utilities built using Node.js are:
- Node-WebKit Runtime for Node.js applications
- PDFKit For PDF document creation
- Log.io Monitoring system
Node Package Manager
Node Package Manager is the package manager for Node.js. It is used for installation and management of Node.js packages
There is a huge repository of open source libraries or packages which can be consumed in a Node.js or JavaScript application.Package is a collection of files which contains “package.json” as one of the files.This file contains metadata about the package.
Node Package Manager (npm) has following features
- Allows developers to share the code using reusable packages.
- Makes it easier to develop applications which are composed of small number of packages.
Node Package Manager is developed entirely in JavaScript.
Executing application
Node for windows environment can be installed from the below url
Once we have installed Node.js on our machine ,we can start working with Node using REPL which is an interactive command line environment ,such as windows command prompt.REPL stands for:
- Read Read the input
- Eval Evaluate the input
- Print Print the output
- Loop Repeat the above cycle until user exits the environment.
REPL can be used for executing the statement and immediately viewing the results.Open the command prompt and type “node” which will launch the node REPL.
Following is a simple program we typed at the node REPL
C:\Users\ashish>node > var a="Hello"; var a="Hello"; undefined > var b="Node" undefined > var c=a+b; undefined > c 'HelloNode' >
Simple Chat application in Node.js
One important thing to remember is that Node.js is that client requests runs on the same thread unlike other web servers.In web servers such as apache or IIS each client request executes on a new thread.So use of system resources such as memory increases with every request.
For I/O intensive tasks this can be limiting as the useful system resources are wasted when the client is waiting for the response.
One of the best use of Node.js is for developing chat application using a concept known as long polling.In a normal HTTP request a web client such as browser makes a request to web server.The server responds with the requested data and the connection is closed.So in a normal HTTP request client is the initiator of the request.
This request-response pattern is suitable for most of the web applications.
HTTP protocol uses Request Response message exchange
In long polling the connection between the client and server is kept open.When the data is available on the server it responds with the data.After this client sends another request.So the process is repeated.
Message exchange in Long Polling
Long polling is suitable for applications in which server doesn’t need to respond immediately. One such application is a chat application.
When one user sends a message to another user on a chat ,the second user may not respond immediately.This calls for the long polling pattern.
Create the server using the http module.http module provides the createServer() method which can be used to create and start a http server.
The following will create and start a server that will listen for requests on port 1337.
Create server and define the callback function
var http = require('http'); var app = http.createServer(function (request, response) { }).listen(1337)
The parameters in the above call back function are:
request contains the request information
response used for sending the response
listen method starts the server at the port 1337
Read file using “fs” module
To access and read a file on the file system we use the ‘fs’ module.Both ‘fs’ and ‘http’ are installed by default.
var fs = require('fs');
Now we will modify our prior code to create the server with the following code.This will return the contents of the file to the requesting client.
Now we will read the chat client and return it to the requester.
var app = http.createServer(function (request, response) { fs.readFile("client.html", 'utf-8', function (error, data) { response.writeHead(200, {'Content-Type': 'text/html'}); response.write(data); response.end(); }); }).listen(1337);
readfile reads the contents of the file
function is the callback function
error contains error information
data contains the file data
response.write(data) sends the contents of the file to the client
Returning the data to the client using “socket.io”
We declare socket.io variable as
var io = require('socket.io');
Listen for the client requests
Declare a call back for the connection action.This executes everytime a client socket connects to socket.io module on the server.Socket represents the client socket.This can be used to write data to the client
var listener = io.listen(server); listener.sockets.on('connection', function(socket) { io.sockets.emit("message",{' message': 'hello client' }); }
Following returns data to all the clients
io.sockets.emit("message",{' message': 'hello client!' });
Leave a Reply