Monday, October 17, 2016

process.nextTick() vs setImmediate() vs setTimeout() in node


Process management in Event loop


setTimeout() :

Definition: setTimeout is used to schedule a function  after some time in future ,i.e the function will run after given time.

Example
console.log("first") ;
setTimeout(function(){
console.log("second");
},2000); 
console.log('third');

Output: 

first
third


second

To understand setImmediate we must first understand few terms: 

Event Queue: This is a queue where all the callbacks/events gets stored while event loop is busy.

Tick: Each time the event loop takes callbacks/events from the event Queue for processing this is called tick.   


setImmediate() :-

Defination: setImmediate is used to schedule a function at end of the event queue (after all callbacks/events present at that time in event queue).

This is used for heavy CPU processing operations. These heavy operations can be scheduled at last using above functions so that other callbacks/events does not wait in the queue for completion of heavy tasks.

Example
console.log("first");
setImmediate(function(){
console.log("second");
});
console.log("third");

Output: 

first
third
second

Note: SetImmediate takes precedence over setTimeout & setImterval but not other callbacks.

process.nextTick(): - 

Defination: process.nextTick is used to schedule a function at front of event queue(before all callbacks/ event s waiting in the event queue).

This method is used when you want  to run some function in a fresh call stack like highly recursive functions.Since process.nextTick() puts the function on top of the event queue.So after completion of the current executing code , the event loop starts processing next function present in event queue which is you process.nextTick function in an fresh call stack.

Example
console.log("first");
process.nextTick(function(){
console.log("second");
});
console.log("third");

Output: 
first
third


second

Difference between setImmediate and process.nextTick:

process.nextTick adds in front of all callbacks and event loop while setImmediate adds at the end.

Example:
for(var i=0;i<3;i++){
fs.readFile("abc.mkv",function(err, data){
if(err){
console.log(err);
}else{
setImmediate(function(){
console.log("completed set immediate");
});
console.log("completed calback");
}
});
}
console.log('event emitted');

Output:

In the above example, I am reading a file in a loop for 3 times.After the file is read i.e  the callback returns , i have used setImmediate with a function that needs to be added in the event queue.This is simple function that prints some message in the console.
As you can see here that, "completed set immediate" is printed at last . This shows that   these were added at end of callback of read file.

Running the same function process.nextTick();
for(var i=0;i<3;i++){
fs.readFile("abc.mkv",function(err, data){
if(err){
console.log(err);
}else{
process.nextTick(function(){
console.log("completed set immediate");
});
console.log("completed calback");
}
});
}

Output:

As you can see in the output, completed set immediate is printed as soon the current callback execution is over.that means the process.nextTick adds in top of the event queue. 

Friday, October 14, 2016

Understanding Closures and its uses In JavaScript


Understanding Closures in Details and  using it practically In JavaScript 


Basic understanding:

A closure is an inner function that has access to outer function variables.

Example:

function foo(){
var name = "furious";
function zoo(){
return "your name is "+ name;
}
return zoo();
}
foo();

As you can see the inner zoo function can access outer foo function variable name.

Practical Implementation/Use:

  • Creating a variable that retains its value in multiple executions like static variables in Java.
    Example: Creating a counter that is incremented on each page view.
    Lets take the below function and check its output.
var counter = function(){
var count = 0;
++count;
console.log(count);
}
}
counter();
counter();
counter();

Output:
1
1
1


As you can see each time the output is 1 because the counter value is always initialized by 0 when the program is executed multiple times.

Now Lets take below example:
var counter = function(){
var count = 0;
return function(){
++count;
console.log(count);
}
}

var increment_pageviews = counter();

increment_pageviews();
increment_pageviews();
increment_pageviews();

Output : 

1
2
3

Run increment_pageviews() multiple times and you can see that the value is  incremented each time.So in above example the value of count is retained.


  • Creating a private variable that cannot be accessed outside the function and its value can only be changed by internal functions like private data members in Java.

    Example: Expanding above example of counters :
  • var counter = function(){
    var count =0;
    return {
    increment : function(){
    console.log (++count);
    return count;
    } ,
    decrement: function(){
    console.log(--count);
    return count ;
    },
    reset : function(){
    count =0;
    console.log(count);
    return count;
    }
    }
    }

    var pageviews = counter();
    pageviews.increment();
    pageviews.increment();
    pageviews.increment();
    pageviews.decrement();
    pageviews.reset();

    output :

    1
    2
    3
    2
    0

    As we can see here that count is a private variable  and can only be manipulated by 3 exposed public function increment(), decrement() & reset() only.

    Deeper Dive into Closures

    Let us take the below example: 
    function add(int x){
    var count = 0 ;
    return function(){
    count += x;
    console.log(count);
    return count;
    }
    }

    var sum = add(3);
    sum();
    sum();
    sum();

    Output:
    3
    6
    9

    Now If the concept of closures was not present , then the above function would have given below output :
    3
    3
    3

    Lets see how closures helps to retains the value of the count variable.
    Now, As we know each function in the javascript has his own heap space where it keeps its variables and reference of the inner functions.
    Also when the function execution is completed & there is no reference for that function i.e there is no reference available for that function the garbage collector clears the heap and remoes all the items in that memory.

    In case of above example
    the first heap area is created for the file, which stores the empty variable sum and reference to function add().

    When add(3) is executed , Another heap area is created  which stores the variable count & reference for inner anonymous add function.

    The reference of this inner anonymous function is also stored in the sum variable of the parent heap.
    Now after the execution of the add function is completed , ideally the count variable must have destroyed. But since there is one more variable sum in the main/parent heap which is having the reference of the inner anonymous function , the heap of add function is not cleaned by garbage collector.So whenever the sum function is called the value stored in the parent heap is incremented & returned. This is the reason why the value of the count is retained in every call .

    Please refer below video for more detailed study of this feature called closure:







    Wednesday, October 12, 2016

    Installation of AngularJs in Windows Machine using Sublime text editor


    Steps For Installing AngularJs in Windows Machine


    Note: Here we are using Xampp server to Host our Web application.
    • There are many IDE available to develop AngularJS code in web apps. We will be using 'Sublime Text3' which is very lightweight and good for AngularJs  web development
      Download install the 'Sublime Text 3' software as per your OS (32 bit or 64 bit).
    •  Install AngularJs package Manager in Sublime Text. An excellent package manager  can be found at:-
       

      It can be used to install a variety of editor enhancements (packages) also such as the AngularJS package which I’ll discuss here so I highly recommend getting it installed. Open above link and download the package manager file link ( 'Package Control.sublime-package' hyperlink available at right side of the page) is given at the right side of the page, file will automatically will download.
    • Move the downloaded package in sublime location:
      • Open Sublime Text 3 text editor
      • Click on Preference --> Browse packages
      • New windows of sublime package location will appear and move the downloaded package to this location.
      • Restart the Sublime Text Editor
    • Install the AngularJS Package:
      • Press ctrl+shift+p (Windows) to open the command pallet in sublime Text editor.
      • Type Package (Package controll: Install Package) and select Install Package from the options which appears after hitting 'ctrl+shift+p'
      • Once the Install Package dialog displays enter AngularJS and press enter.
    • Congratulations, You have done with your AngularJS setup. Now if you have installed Xampp in C drive, please go in 'Xampp' folder which resides 'C:\xampp' in location.
      Click on xampp-control.exe and start the apache service.

    • Create a folder inside the 'C:\xampp\htdocs\' and provide a name as per your project. Create a hello.html file and write a simple program of AngularJS and test it in bowser.
    NOTE : Please refer the link for AngularJS or download the library of AngularJS and include it in your file so that you can use the library to develpe the code in AngularJS.

    Refer below links for more tutorials and references.

    AngularJS Lib: https://angularjs.org/


    Thursday, October 6, 2016

    Alphanumeric Sorting in JavaScript using sort function


    Sorting using sort() function in JavaScript


    Function sort() is basically used for sorting an array in JavaScript.

    Let us take few sample codes and see how this function behaves with arrays of different types of elements such as numbers , strings , alphanumeric etc.

    Example 1: 
    var ar = [11,23,7,189,9,550];
    var result = ar.sort();
    console.log(result);

    Output: [ 11, 189, 23, 550, 7, 9 ]
    • Conclusion : The above example sorts the array of Numbers is lexical / dictionary order.

    Example 2: 
    var ar = [11,23,7,189,9,550];
    var result = ar.sort(numberic_sort);
    console.log(result);

    //This function cannot be used for string comaprision
    function numberic_sort(a,b){
    return a-b;
    };

    Output : [ 7, 9, 11, 23, 189, 550 ]
    • Conclusion : The above customized function sorts the array of numbers in ascending order.

    Example 3:
    var ar = ["as","asddd","trhs","oocww","wfewf","kcnw","qmdkvcn","acwwev"];
    var result = ar.sort();
    console.log(result);

    Output: 
    'acwwev',
    'as',
    'asddd',
    'kcnw',
    'oocww',
    'qmdkvcn',
    'trhs',
    'wfewf' ]
    • Conclusion : The above example sorts the array of Strings is lexical / dictionary order.

    Example 4:
    var ar = ["csnc33","cddsc1","cwew91","fdwef62","vc2211","2831nb1","7dsv7sv","ncnd777","22nbebe","ewfwef873bttbbbbbgc","fdwef69","fdwef61","123","njahy","125","0.342"];
    var result = ar.sort();
    console.log(result);

    Output : [
    '0.342',
    '123',
    '125',
    '22nbebe',
    '2831nb1',
    '7dsv7sv',
    'cddsc1',
    'csnc33',
    'cwew91',
    'ewfwef873bttbbbbbgc',
    'fdwef61',
    'fdwef62',
    'fdwef69',
    'ncnd777',
    'njahy',
    'vc2211' ]
    • Conclusion : The above example also sorts the array of Strings is lexical / dictionary order.

    Example 5:
    var ar = ["A","a","1",1,"cascsac","cccead","treave","mvwen","VV344FFVveve323","v8e8v98vvd","3234223","3332csdvv3","323","3451","68564","11243","562",45,2352,255,0.432,64.223,"5545.454"];
    var result = ar.sort();
    console.log(result);

    Output : 
    0.432,
    1,
    '1',
    '11243',
    2352,
    255,
    '323',
    '3234223',
    '3332csdvv3',
    '3451',
    45,
    '5545.454',
    '562',
    64.223,
    '68564',
    'A',
    'VV344FFVveve323',
    'a',
    'cascsac',
    'cccead',
    'mvwen',
    'treave',
    'v8e8v98vvd' ]

    Conclusion: 
    • By default ,All the values are compared as strings in sort function , hence sorting is in lexical/dictionary order.
    • Sorting Order :  numbers -> capital Alphabets -> small alphabets
    • Example  :  [1, "1", "1a", "A" ,"a", "b1"]  (Ascending order) 

    Let us take Some more example , but now with Comparison Operators such as  > , <  , == etc


    • 1 < 2 true
    • "1" < "2"  true
    • "1" == 1  true
    • "1" < "a"   true
    • "1" < "sacacasc"  true
    • "0.3" < "svs"  true
    • "sscsd" < "sscsd8776"  true

    As you can see from above examples that comparison operator also woks similar as sort function.
    It also compares values as strings and hence gives results according to lexical order. 

    Uninstalling MongoDB from ubuntu


    Uninstalling MongoDB from Ubuntu Step-Wise


    Open Terminal in ubuntu using Ctrl+Alt+T.
    Run the below commands :

    • sudo service mongod stop
    • sudo apt-get purge mongodb-org*
    • sudo rm -r /var/log/mongodb
    • sudo rm -r /var/lib/mongodb


    The above commands will remove the MongoDB installation from ubuntu.

    For Reinstalling MongoDB Please refer : Installing MongoDB in Ubuntu.




    Installing MongoDB in Ubuntu


    Step-wise Installation of MongoDB in Ubuntu 


    Note: We will be installing community edition of MongoDB 

    Open Terminal in ubuntu using Ctrl+Alt+T.
    Run the below commands :

    sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927


    # For Ubuntu 12.04
    • echo "deb http://repo.mongodb.org/apt/ubuntu precise/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list

    # For Ubuntu 14.04
    • echo "deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list
    # For Ubuntu 16.04
    • echo "deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list

    sudo apt-get update

    # To install latest stable version of MongoDB
    sudo apt-get install -y mongodb-org


    To install a specific release, you must specify each component package individually along with the version number, as in the following example:

    sudo apt-get install -y mongodb-org=3.2.10 mongodb-org-server=3.2.10 mongodb-org-shell=3.2.10 mongodb-org-mongos=3.2.10 mongodb-org-tools=3.2.10

    Follow the below step only for Ubuntu 16.04

    Create a new file at /lib/systemd/system/mongod.service with the following contents:

    [Unit] 

    Description=High-performance, schema-free document-oriented database After=network.target
    Documentation=https://docs.mongodb.org/manual

    [Service] 

    User=mongodb
    Group=mongodb
    ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf

    [Install]



    WantedBy=multi-user.target

    Commands for Starting, Stopping, restarting MongoDB


    • sudo service mongod start
    • sudo service mongod stop
    • sudo service mongod restart


    To verify that MongoDB is running , check the logs file at below path

    /var/log/mongodb/mongod.log


    This log file must have
    [initandlisten] waiting for connections on port <port>

    If the log file have above line , MongoDB is up and running.

    For Uninstalling  MongoDB , please refer : UnInstalling MongoDB in Ubuntu



    Installing MongoDB in Windows


    Step-wise Installation on MongoDB Current Stable Release (3.2.10)


    Download MongoDB from the below Url 


    The trick here is to download the appropriate version of mongo. There are multiple types of mongo servers but we will use either of Community Server or Enterprise Server.
    Community servers are used for development and testing purposes while enterprise edition is used for commercial purposes .
    Also there are choices for 62bit/32bit . But all these installations are best supported in windows 7 and above.


    Install the downloaded file with all default options.

    Now, Create a directory anywhere which will serve as a root directory for our database.
    e.g mkdir -p C:\mongo\data\db

    Set the MongoDB installation path in environment Variable , if it is not already set.

    By default installation directory is
    C:\Program Files\MongoDB\Server\3.0\bin

    Set above path in environment variable if you have used default installation directory.

    Now we are ready to start MongoDB.
    To start MongoDB  , Run the below command in command prompt:

    mongod --dbpath c:\mongo\data\db

    With --dbpath provide the path root directory created for sorting database.

    If you see below screen without any prompt coming again, then no error has occurred and  MongoDB server is running Successfully.

    To verify that mongo server is running ,Leave this command prompt running.Open new        command prompt and run below command.

    mongo localhost:27017

    This command will try to connect  to MongoDB server running on localhost on port 27017 (By default). If you have mongo running on some different IP and port (custom configuration), you can use those ip:port also.




    Now if you see mongo shell running as shown in below screenshot , than MongoDB is successfully installed and running.








    Wednesday, October 5, 2016

    Installing Specific version of NodeJs in Ubuntu using NVM


    Steps For installing Specific Version of Ubuntu using NVM

    In Order to install specific version of node in ubuntu we will be using a tool called NVM which stands for node version manager.

    NVM helps us to install and manage multiple versions of node in a single machine.It helps to switch between different versions 

    To install NVM , Run below commands in a terminal


    • sudo apt-get update
    • sudo apt-get install build-essential libssl-dev
    • curl -sL https://raw.githubusercontent.com/creationix/nvm/v0.31.0/install.sh | sh

    To gain access to the nvm functionality, you'll need to log out and log back in again, or you can source the~/.profile file so that your current session knows about the changes:

    source ~/.profile
    Now that you have nvm installed, you can install isolated Node.js versions.
    To find out the versions of Node.js that are available for installation, you can type:
    nvm ls-remote
    nvm install 6.0.0

    You can change to what ever version you like.

    Usually, nvm will switch to use the most recently installed version. You can explicitly tell nvm to use the version we just downloaded by typing:
    nvm use 6.0.0

    When you install Node.js using nvm, the executable is called node. You can see the version currently being used by the shell by typing:
    node -v

    If you have multiple Node.js versions, you can see what is installed by typing:
    nvm ls

    If you wish to default one of the versions, you can type:
    nvm alias default 6.0.0

    To remove / uninstall a version
    nvm uninstall 6.0.0

    To Exeute node REPL/command line with specific version
    nvm run 6.0.0

    In NVM, you can also use alias for setting the default version of node
    nvm alias default 6.0.0.

    Each version of Node.js will keep track of its own packages and has npm available to manage these.

    You can learn more about the options available to you with nvm by typing:
    nvm help

    NodeJS installation in Ubuntu

    Step-wise installation of NodeJs in Ubuntu

    Note:  Tested on Ubuntu 14.10

    Open Terminal in ubuntu using Ctrl+Alt+T.
    Run the below commands :

    sudo apt-get update
    sudo apt-get install nodejs
    sudo apt-get install npm

    This should install your NodeJS in Ubuntu.The version installed will be v0.10.* which is old but stable version.
    Use below command to verify the installation 
    nodejs -v 

    If the above installation does not work (as in EC2 & other cloud instances) or For newer LTS versions, try installing NodeJs using PPA.

    Run below commands in the terminal.

    curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash -
    sudo apt-get install -y nodejs

    The above commands will install Nodejs with 4 and above version.
    In order for some npm packages to work (such as those that require building from source), you will need to install the build-essentials package too.

    sudo apt-get install -y build-essential





    NodeJS installation in Windows



    Step-wise installation of NodeJS in windows Machines:


    Download 32/64 bit latest/stable NodeJs installer according to your system compatibility. 

    Note: For beginners , Download windows  64 bit  (.msi) Installer [Long Term Support]  

    The above url will download node version 4.6.0 which also includes npm 2.15.9.The npm is a tool that manages all the modules which are needed by node like installation , up-gradation & removal of node modules .
    Double click the installer and install with default options.
    After the installation is finished, Open the command prompt and type below commands to verify the installation.

    > node -v 
    > npm -v

    The output must give both node & npm versions like below image.



    If the output are the versions , NodeJs is ready to go.

    If the versions are not displayed ,check whether the node is present in environment path.If not, Add node installation directory in environment path. Default is "C:\Program Files\nodejs".

    Check the above commands again .If the versions are still not displayed follow the following steps 

    1. Clear the installation 
    2. Delete installation directory - Default is  C:\Program Files\nodejs 
    3. Remove nodejs from environment path.
    4. Restart the system
    5. Install again.