node.js 1. 2 contents about node.js web requirement latest trends introduction simple web server...
DESCRIPTION
3 Node.js was created by Ryan Dahl in 2009 Node.js is a software platform used to build scalable network (especially server-side) applications Node.js is a packaged compilation of Google's V8 open source JavaScript engine. About Node.JsTRANSCRIPT
Node.Js
1
2
Contents
• About Node.Js• Web requirement latest trends• Introduction• Simple web server creation in Node.Js• Dynamic Web pages• Dynamic web page creation• Loading of dynamic web pages• Asynchronous Programming in Node.Js• Node.Js event loop• Example of sequential programming• Event loop handler based programming• Things to remember while developing Node.Js• Real time communication in Node.Js• Example of Real Time communication-Chat Application.
3
• Node.js was created by Ryan Dahl in 2009
• Node.js is a software platform used to build scalable network
(especially server-side) applications
• Node.js is a packaged compilation of Google's V8 open source
JavaScript engine.
About Node.Js
4
• Real time communication
• Chat, gaming, constant social media updates, collaboration –each of
these features requires real time communication between users,
clients, and servers across the web.
• Server needs to supports large No. of Clients
• Large numbers of clients poll the server simultaneously, hence it
becomes incredibly slow and inefficient.
Web requirement latest trends
5
• Node.js is an event-driven, server-side JavaScript environment.
Node runs JavaScript using the V8 engine developed by Google
for using it in their Chrome web browser.
• Executes JavaScript at lightning speeds
V8 compiles JavaScript in native machine code instead of
executing it as byte code
A wrapper is built around V8 to make it execute JavaScript
without the browser.
Introduction
6
• Node.js is open source and a cross-platform,
Runs on Mac OSX, Windows, and Linux.
It is possible to run a web server without the use of
external software such as Apache.
Allows developers to create a web server with more
control.
Contd…
7
Example : Simple web server creation in Node.js
var http = require("http");
http.createServer(function(request
, response) {
response.writeHead(200,
{"Content-Type": "text/plain"});
response.write("Hello
World");
response.end();
}
}).listen(8080);
8
Dynamic web pages
• We can create a dynamic web page in the node.js
like php, jsp, jinja (Python)
• Jade – template engine can create a dynamic web page in node.js
9
<!DOCTYPE html><html lang="en"> <head> <title>NP Compete</title> <script type="text/javascript"> if (foo) { bar(1 + 5)} </script> </head> <body> <h1>NP Compete </h1> <div id="container" class="col"> <p>Welcome to Node.js Programming</p> <p> Jade is a simple templating language with a strong focus on performance and powerful features. </p> </div> </body></html>
Rendered HTML pageThis is the node.js example for dynamic webpage creation.
doctype 5html(lang="en") head title= NP Compete script(type='text/javascript'). if (foo) { bar(1 + 5) } body h1 NP Compete #container.colp Welcome to Node.js Programming p Jade is a simple templating language with a strong focus on performance and powerful features.
Dynamic web pages creation
10
How dynamic web page gets loaded. var http = require("http"),fs = require('fs');
http.createServer(function(request, response) { fs.readFile(__dirname +
'/index.html', function (err, data) { if (err) { res.writeHead(500); return res.end('Error loading index.html'); }
res.writeHead(200); res.end(data); });
}}).listen(8080);
Read file is used to read the HTML file ( index.html) and send it back to the client.
11
• The execution model of Node.js is different from other web servers
• There is only one single process.
• It has Event Loop to achieve multiple task execution.
• In other web servers each request will create a separate process.
• OS requires separate effort i.e memory and time for each process
creation.
Asynchronous Programming in Nodejs
12
• To scale large volumes of clients, all I/O intensive operations in
Node.js are performed asynchronously.
• When a Node application needs to perform a blocking operation (I/O
operations, heavy computation, etc.) it sends an asynchronous task to
the event loop, along with a call-back function, and then continues to
execute the rest of its program.
• The event loop keeps track of the asynchronous operation, and
executes the given call-back when it is completed
Contd…
13
Node.js Event Loop
14
Example of sequential programming
var result = database.query("SELECT * FROM hugetable");
console.log("Hello World");
• In this example the first line queries a database for number rows
and the second line prints "Hello World" to the console.
• Let's assume that the database query is really slow, then it will
take several seconds to display the message in the console.
• This is not an efficient programming since the JavaScript
interpreter of Node.js has to first read the complete result set
from the database, and then it can execute the console.log()
function.
15
database.query("SELECT * FROM
hugetable", function(rows) {
var result = rows;
});
console.log("Hello World");
• Nodejs takes the query and sends it to the database. But instead of
waiting for it to be finished, it immediately executes the console.log(),
• When the database server has completed the operation it sends the
result of the query that executes the function passed to
database.query()
Event Loop handler based programming
16
Things to remember while developing Node.JS
• While writing the program in Nodejs we need to keep in mind
that all the complex operations are not mapped to single event
loop.
• It needs to be to be subdivided into smaller independent
operations and given to the event loop to achieve the best
performance.
• In the below code we have shown that complex I/O operation
has been performed.
17
var http = require("http");var sleep = require('sleep'); // sleep here refers to - complex I/O operationhttp.createServer(function(request, response) {
//while(true)//{
response.writeHead(200,{"Content-Type": "text/plain"});
response.write("Hello World"); response.end();
sleep.sleep(20); // it waits for till the I/O operation.
//}}).listen(8888);
Contd…
18
Real time communication in Nodejs• Normal scenario requires the client to send a request and the server
sends the data to the client.
• In node js because of the socket programming ( which is a persistent
connection in node js) it is possible to perform real time
communication between the client and the server.
• We have shown an example of live communication i.e. group chat
between multiple user.
• Here we can see that when one user send a chat message to the
server, it broadcasts the chat message to all the other users
immediately without any periodic request from the client .
19
var app = require('http').createServer(handler) io = require('/usr/local/lib/node_modules/socket.io').listen(app) fs = require('fs')var sockets = [];app.listen(8080);
function handler (req, res) { fs.readFile(__dirname + '/index.html', function (err, data) { if (err) { res.writeHead(500); return res.end('Error loading index.html'); } res.writeHead(200); res.end(data); });}io.sockets.on('connection', function (socket) { socket.emit('message', { msg: 'welcome to the chat' }); socket.on('send', function (data) { io.sockets.emit('message', data); });});
Example - Chat Application Server side code
20
<!DOCTYPE html><html lang="en"> <head> <title>Jade</title> <script src="/socket.io/socket.io.js"></script><script> var socket = io.connect('http://localhost'); socket.on('message', function (data) { // Socket on listens to the server and gets executed immd when it gets the data from the server. console.log(data);
document.getElementById("masg").innerHTML = document.getElementById("masg").innerHTML +"<br>"+data.msg; });function sendMsg() { if(document.getElementById("msgTxt").value == "") { alert("Please type Message!"); } else { var text = document.getElementById("msgTxt").value; socket.emit('send', { msg: text}); } };</script> </head> <body> <h1>Message</h1> <div id="masg"></div> <input type="text" value="" id="msgTxt"/><a href="javascript:sendMsg();">Send</a> </body></html>
Client side code
Contd…
Thank You!!!
21