Sunday, June 29, 2014

Handle process in [Node.js]

Use of process handle:

 Some time When you write program , before end of your program you want to clear some connection , thread, memory . In such case while terminate your process you need to write some code.

In Node.js The process object is a global object and can be accessed from anywhere. 

Who will handle method in process.

 Node.js runtime process will call handlers assign in process objects.


How to use.

 process.on('exit', function(code) {  
  console.log("On Exit Start");  
  setTimeout(function() {  
   console.log('This will not run');  
  }, 1000);  
  console.log('About to exit with code:', code);  
 });  
 console.log("Current Time-"+new Date());    
  var timerId=setTimeout(function(){   
  console.log("Current Time-"+new Date());    
  }, 5000);   




Tuesday, June 10, 2014

Timeout and Interval Timers In [Node.js]

Timer is use for running asynchronous Thread in Node js program.


API For Timer 

setTimeout(callback, delay, [arg], [...])
clearTimeout(timeoutObject)
setInterval(callback, delay, [arg], [...])
clearInterval(intervalObject)


How it works - setTimeout-clearTimeout.

To schedule a function execution of a one-time callback after delay milliseconds. Returns a timeoutObject for possible use with clearTimeout(). Optionally you can also pass arguments to the callback
setTimeout
 console.log("Current Time-"+new Date());   
 setTimeout(function(){  
  console.log("Current Time-"+new Date());   
 }, 1000)  







clearTimeout
 If you started any thread or task using settimeout you can kill/stop that using clearTimeout.

 console.log("Current Time-"+new Date());   
 var timerId=setTimeout(function(){  
  console.log("Current Time-"+new Date());   
 }, 5000);  
 clearTimeout(timerId);  

 In this case 2nd Current Time won't print because we clear the timer with ID




How it works - setInterval-clearInterval.

To schedule the repeated function  execution of callback every delay milliseconds. Returns a intervalObject for possible use with clearInterval(). Optionally you can also pass arguments to the callback.

 console.log("Current Time-"+new Date());   
 setInterval(function(){  
  console.log("Current Time-"+new Date());   
 }, 1000)  



clearInterval
 If you started any thread or task using setInterval you can kill/stop that using clearInterval.

 console.log("Current Time-"+new Date());   
 var counter=0;  
 var timerId=setInterval(function(){  
  console.log("Current Time-"+new Date());   
  counter++;  
  if(counter==3)  
  {  
   console.log("clearInterval after 3");  
   clearInterval(timerId);  
  }  
 }, 1000);  

  In this case After 3 sec Interval will stop  because we clear the interval with ID


Wednesday, May 28, 2014

Optimize Your Site With Zlib Compression [Node.js]

Running a gzip operation on every request is quite expensive.

It would be much more efficient to cache the compressed buffer.

But "Compression is a simple, effective way to save bandwidth and speed up your site."

How it works.
In this case we are sending different encoding request to server .
Server compress data according to Encoding .
And server will response compress data . [So that file will download fast as size reduced]
Then client responsibility to decompress data . [As its decompress quite expensive . Still all modern browser supports this ]



Example Encoding Client :: EncodingClient.js

 // client request example  
 var zlib = require('zlib');  
 var http = require('http');  
 var fs = require('fs');  
 var readline = require('readline');  
 var rl = readline.createInterface({  
   input: process.stdin,  
   output: process.stdout  
 });  
 var acceptEncoding = null;  
 rl.question("\nWhat type accept-encoding you want to set for this request gzip/deflate/no? ", function (answer) {  
   // TODO: Log the answer in a database  
   if (answer === "gzip" || answer === "deflate") {  
     console.log("\nRequest with encoding ::", answer);  
           acceptEncoding = answer;  
   }else{  
           acceptEncoding=null;  
           console.log("\nRequest with no encoding");  
      }  
   rl.close();  
   var request = http.get({  
     host: 'localhost',  
     path: '/',  
     port: 8585,  
     headers: {  
       'accept-encoding': acceptEncoding  
     }  
   });  
   request.on('response', function (response) {  
     switch (response.headers['content-encoding']) {  
       // or, just use zlib.createUnzip() to handle both cases  
     case 'gzip':  
       var length = 0;  
       var gzippipe = response.pipe(zlib.createGunzip(), {  
         end: false  
       });  
       response.on('data', function (chunk) {  
         length = length + chunk.length;  
       });  
       response.on('end', function () {  
         console.log("gzip Encoding Response Data Length ::" + length);  
       });  
       var output = fs.createWriteStream('Download_gZip_Ticket.pdf');  
       gzippipe.pipe(output);  
       break;  
     case 'deflate':  
       var length = 0;  
       var deflatepipe = response.pipe(zlib.createInflate(), {  
         end: false  
       });  
       response.on('data', function (chunk) {  
         length = length + chunk.length;  
       });  
       response.on('end', function () {  
         console.log("deflate Encoding Response Data Length ::" + length);  
       });  
       var output = fs.createWriteStream('Download_deflate_Ticket.pdf');  
       deflatepipe.pipe(output);  
       break;  
     default:  
       var length = 0;  
       var output = fs.createWriteStream('Download_normal_Ticket.pdf');  
       response.pipe(output, {  
         end: false  
       });  
       response.on('data', function (chunk) {  
         length = length + chunk.length;  
       });  
       response.on('end', function () {  
         console.log("deflate Encoding Response Data Length ::" + length);  
       });  
       break;  
     }  
   });  
 });  

Example Encoding Server :: EncodingServer.js

 var zlib = require('zlib');  
 var http = require('http');  
 var fs = require('fs');  
 console.log("Startd Server");  
 http.createServer(function (request, response) {  
   console.log("Request Received");  
   var raw = fs.createReadStream('Ticket.pdf');  
   var acceptEncoding = request.headers['accept-encoding'];  
   if (!acceptEncoding) {  
     acceptEncoding = '';  
   }  
   console.log("Request acceptEncoding=" + acceptEncoding);  
   if (acceptEncoding.match(/\bdeflate\b/)) {  
     response.writeHead(200, {  
       'content-encoding': 'deflate'  
     });  
     raw.pipe(zlib.createDeflate()).pipe(response);  
   } else if (acceptEncoding.match(/\bgzip\b/)) {  
     response.writeHead(200, {  
       'content-encoding': 'gzip'  
     });  
     raw.pipe(zlib.createGzip()).pipe(response);  
   } else {  
     var length = 0;  
     response.writeHead(200, {});  
     raw.pipe(response);  
   }  
 }).listen(8585);  

How to Execute:




Tuesday, May 27, 2014

Handle Gun Zip File In [Node.js]

Zlib  provides bindings to Gzip/Gunzip classes to compress files .


How to access this module with:

 var zlib = require('zlib');  


How to create a Gun zip file:


 var zlib = require('zlib');  
 var gzip = zlib.createGzip();  
 var fs = require('fs');  
 var inp = fs.createReadStream('input.txt');  
 var out = fs.createWriteStream('input.txt.gz');  
 inp.pipe(gzip).pipe(out);  



How to Unzip a Gun zip file:

 var zlib = require('zlib');  
 var gunzip = zlib.createGunzip();   
 var fs = require('fs');   
 var inp = fs.createReadStream('input1.txt.gz');   
 var out = fs.createWriteStream('input1_unzip.txt');   
 inp.pipe(gunzip).pipe(out);  



Monday, May 19, 2014

Read Line in [Node.js]

Readline allows reading of a stream (such as process.stdin) on a line-by-line basis.

How to Use:

 var readline = require('readline');  
 var rl = readline.createInterface({  
  input: process.stdin,  
  output: process.stdout  
 });  
 rl.question("What do you think of node.js? ", function(answer) {  
  // TODO: Log the answer in a database  
  console.log("Thank you for your valuable feedback:", answer);  
  rl.close();  
 });  

How to execute: