Network I/O Is Unpredictable: Node.js

We’ve seen the importance of callback method in our previous video tutorials. Now lets see how networked I/O Is unpredictable.


http-module-get-method-nodejs-network-io-unpredictability

Here we request/ping for information from 3 different servers and look at its response time. Each time we send a request, we get different response time depending upon how busy the server is, its bandwidth etc.

JavaScript File
app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var http= require("http"),
      urls  = [ "technotip.org",
         "technotip.com",
      "www.capturecaption.com"
       ];
 
for(var i = 0; i < urls.length; i++){
ping( urls[i] );
}
 
function ping( url ){
var start = new Date();
 
http.get({ host: url }, function(res){
console.log("URL :"+url);
console.log("Response Time: "+(new Date() - start)+" ms");
});
}

Here we require http module, which is built into nodejs, and store it inside a local object called http. We also declare and initialize an array with 3 domain names. Using for loop, we loop through each URL present in the urls array and pass it to a method called ping();

Inside ping method, we record client system date in a variable before sending a request to the server(via URL). Now using http objects get method we send request to the server and see it’s response time. get method takes 2 parameter, first parameter is an object which contains host information – the host url { host: url }. Second parameter is a callback method which automatically gets an object which is returned by first parameter {host: url}. Inside the callback method, we subtract the new system date with the one we recorded before requesting for a response, this way we calculate the response time of each URL.

HTTP get method: Node.js


[youtube https://www.youtube.com/watch?v=vktKMtWoPbA]

YouTube Link: https://www.youtube.com/watch?v=vktKMtWoPbA [Watch the Video In Full Screen.]



output
C:\node>node app.js
URL :technotip.com
Response Time: 1462 ms
URL :www.capturecaption.com
Response Time: 1993 ms
URL :technotip.org
Response Time: 2004 ms

C:\node>node app.js
URL :technotip.com
Response Time: 1381 ms
URL :www.capturecaption.com
Response Time: 1702 ms
URL :technotip.org
Response Time: 1871 ms

C:\node>node app.js
URL :technotip.com
Response Time: 1409 ms
URL :www.capturecaption.com
Response Time: 1628 ms
URL :technotip.org
Response Time: 2001 ms

C:\node>node app.js
URL :technotip.com
Response Time: 1512 ms
URL :www.capturecaption.com
Response Time: 1534 ms
URL :technotip.org
Response Time: 1899 ms

Each time we execute the script, we get different response time, and the order of URLs may also differ, as we can’t predict which server will respond first.

HTTP Server(request/response) Counter Application: Node.js

This video tutorial is a rapid application development to illustrate HTTP Server(request/response) using Node.js

In this video, we use HTTP Server(request/response): Node.js code and work on it to develop a simple counter application.

Using this application, we can know how many visits have been made since the last server down time!

For explanation of all the keywords and working, please visit HTTP Server(request/response): Node.js

HTTP Server
count.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 var http = require('http');
 var visits = 0;
 
 http.createServer( function(request, response) {
 
console.log('New Connection');
visits++;
 
response.writeHead(200, { 'Content-Type':'text/plain' } );
response.write('Hello\n');
response.write('We have had '+visits+' visits');
response.end();
 
 }).listen(8080);
 
 console.log('Server Started..');

Here we take a variable called visits and initialize it to 0.
Once there is a new connection request, we increment it’s value by 1.
Since there is also request from favicon, practically, there’ll be 2 requests simultaneously: hence the counter increments by 2 for each new connection request.

using write method, we print the number of visits.

HTTP Server(request/response) Counter Application: Node.js


[youtube https://www.youtube.com/watch?v=yRaMJy5Mot0]

YouTube Link: https://www.youtube.com/watch?v=yRaMJy5Mot0 [Watch the Video In Full Screen.]



Output:
Hello
We have had 3 visits

Note:
Once you stop the server or whenever there is down time in the server, the counter is reinitialized once the server is restarted.

Make use of Database to store the counter value, if you need it inspite of server downtime or restarts.

HTTP Server(request/response): Node.js

This video tutorial illustrates working of simple HTTP Server, using Node.js
We’ll show the request, response of our HTTP server using simple Node.js program.

We’ll create a HTTP Server, with some response text in it.
Then, send request using web browser and see to that our HTTP server responds appropriately.

HTTP Server
hello.js(using chaining of methods)

1
2
3
4
5
6
7
8
9
10
11
var http = require('http');
 
http.createServer( function(request, response){
 
 response.writeHead(200, { 'Content-Type': 'text/plain' });
 response.write('Welcome to Node!');
 response.end();
 
}).listen(8080);
 
console.log('Server Started');

OR

hello.js(without using chaining of methods)

1
2
3
4
5
6
7
8
9
10
11
12
13
var http = require('http');
 
var server = http.createServer( function(request, response){
 
 response.writeHead(200, { 'Content-Type': 'text/plain' });
 response.write('Welcome to Node!');
 response.end();
 
});
 
server.listen(8080);
 
console.log('Server Started');

In the first line, we require http module of node.js
http module is built into node.js package, to help build node.js applications.

Using this http, we’ll call createServer method, which returns an object. Using this object we’ll call another method listen and pass port number 8080 to be(reserve to be used) used to invoke our HTTP server.

createServer method takes a anonymous function as parameter.

Anonymous function: Method with no name.

This anonymous method takes two parameters: request and response.

request and response: These are two objects passed by our http server when it receives new connection requests.

Using response object we’ll call writeHead method and pass 2 parameters.
First being the status code: 200 (which means, everything is ok or successfully connected)
Second parameter specifies that, the content type is plain text.

Inorder to demonstrate that our HTTP server is indeed responding/working, we’ll output a simple string “Welcome to Node” onto our web browser, as a response text.

Using the object returned by createServer method, we’ll invoke another method called listen and then reserve port number 8080 for our HTTP Server request.

Server Start
To indicate the server start, using simple console.log we’ll indicate its start.

node-http-server-start

Server Start
Command Prompt

1
node hello.js

Navigate to the folder where hello.js file is located. Now using node command execute hello.js file.

Once “Server Started” message is given, open any web browser and goto localhost:8080 to ping / request our HTTP server.

HTTP Server ( Request / Response ): Node.js


[youtube https://www.youtube.com/watch?v=9DFbfXcSIOw]

YouTube Link: https://www.youtube.com/watch?v=9DFbfXcSIOw [Watch the Video In Full Screen.]



Output:
Welcome to Node!

Note:
If you make changes to the response text(as in our example), you’ll need to restart the server in order for the changes to reflect at the client end.

Close the server connection using ctrl+ c and restart it using node command followed by file name.