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.

callback methods / anonymous functions: jQuery

Today lets see how callback methods or anonymous functions work. We also show you the anatomy of callback methods.

callback-method-anonymous-function-javascript-jquery-nodejs

callback methods are very important for achieving asynchronous way of coding.

HTML file
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
< !DOCTYPE html>
<html>
<head>
<title>callback or anonymous function</title>
<script src="jquery-1.10.2.min.js"></script>
<script src="myScript.js"></script>
</head>
<body>
 
<p></p>
<div></div>
 
</body>
</html>

Here we have included jQuery library and myScript.js We also have a paragraph tag and a div tag, to be filled with some data by myScript.js file.

JavaScript file
myScript.js

1
2
3
4
$(document).ready(function(){
 $("p").hide("slow");
 alert("Stop!");
});

Here the paragraph hide is called and before it finishes hiding, alert is called and every other operation of the webpage is halt until the user responds to the alert window. But if we want the paragraph to be hidden first and only after the paragraph is completely hidden we need to call the alert, in such case use callback methods as shown below:

JavaScript file: callback method
myScript.js

1
2
3
4
5
$(document).ready(function(){
 $("p").hide("slow", function(){
        alert("Stop!");
 });
});

If you want multiple things to occur after hiding the text(in above case) , you can nest the callback methods.

Anatomy of callback methods
JavaScript file: callback method
myScript.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$(document).ready(function(){
eat("pizza", "cola", function(){
$("div").html("I had my food!");
});
 
});
 
function eat(food, drink, callback)
{
$("p").html("I ate "+food+" and had a "+drink);
 
if(callback && typeof(callback) === "function" )
{
callback();
}
 
}

Here we have a method called eat, which takes 3 parameters. First two are variable type and the 3rd parameter is a function type argument.

Once the page loads, we call eat method and pass pizza, cola and a callback method to it. After the first 2 variable values are displayed, eat method checks if the 3rd parameter is actually present and is a function – if so, it’ll call the function. So, the callback method is called after its preceding arguments are processed.

Anatomy and Working of Callback methods / anonymous functions


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

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



Examples:
1. If we have calls to Facebook API, Twitter API and Google Finance API’s: Using JavaScript(jQuery or nodejs) we could send the request to all these API’s concurrently and not worry much about its response time. Once any of these API’s respond, the corresponding callback methods are called. So while these scripts are executed, it binds the callback methods to its calls, and then stops worrying about its response!

2. Many ad networks have implemented asynchronous ad codes, since these codes use callback methods and there is no need for the webpage to wait until the ad server responds. If and when the ad server responds with an ad, the page or the ad spot is filled with the ad.