<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Rajesh T</title>
    <description>The latest articles on Forem by Rajesh T (@rajesh04159786).</description>
    <link>https://forem.com/rajesh04159786</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F325769%2F1a396082-00a2-4ff8-80f1-dc23cdbab356.jpg</url>
      <title>Forem: Rajesh T</title>
      <link>https://forem.com/rajesh04159786</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/rajesh04159786"/>
    <language>en</language>
    <item>
      <title>Shallow copy vs Deep copy of JavaScript object</title>
      <dc:creator>Rajesh T</dc:creator>
      <pubDate>Thu, 08 Oct 2020 08:30:05 +0000</pubDate>
      <link>https://forem.com/rajesh04159786/shallow-copy-vs-deep-copy-of-javascript-object-1abb</link>
      <guid>https://forem.com/rajesh04159786/shallow-copy-vs-deep-copy-of-javascript-object-1abb</guid>
      <description>&lt;p&gt;&lt;a href="https://www.linkedin.com/pulse/copy-object-rajesh-t"&gt;https://www.linkedin.com/pulse/copy-object-rajesh-t&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Sharing data between routed components in Angular 10</title>
      <dc:creator>Rajesh T</dc:creator>
      <pubDate>Thu, 23 Jul 2020 07:04:10 +0000</pubDate>
      <link>https://forem.com/rajesh04159786/sharing-data-between-routed-components-in-angular-10-33o0</link>
      <guid>https://forem.com/rajesh04159786/sharing-data-between-routed-components-in-angular-10-33o0</guid>
      <description>&lt;p&gt;&lt;a href="https://www.linkedin.com/pulse/passing-data-between-components-routing-rajesh-t"&gt;https://www.linkedin.com/pulse/passing-data-between-components-routing-rajesh-t&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>JavaScript compiler , Scope &amp; TDZ in depth</title>
      <dc:creator>Rajesh T</dc:creator>
      <pubDate>Fri, 15 May 2020 07:28:15 +0000</pubDate>
      <link>https://forem.com/rajesh04159786/javascript-compiler-scope-tdz-in-depth-pf</link>
      <guid>https://forem.com/rajesh04159786/javascript-compiler-scope-tdz-in-depth-pf</guid>
      <description>&lt;p&gt;&lt;strong&gt;JavaScript is a compiled &amp;amp; interpreted language&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;Most of the beginners  can confuse about this statement. When we are coming from C, C++ background, where the those compilers can compile our code into low level, the &lt;em&gt;JavaScript compiler&lt;/em&gt; is different than that.&lt;/p&gt;

&lt;p&gt;To understand the role of compiler in JavaScript,We should know about roles of &lt;em&gt;JavaScript Engine&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--zGsrPNli--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/499h8jaso7eyevst91ad.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--zGsrPNli--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/499h8jaso7eyevst91ad.jpg" alt="Alt text of image" width="880" height="369"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now let us understand the role of compiler with an example.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;var data=100;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It is variable declaration and initialization.Even though it is appearing as single statement,Actually, &lt;br&gt;
" &lt;strong&gt;It is combination of two different actions which can occur at two different situations&lt;/strong&gt; " &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Action-1&lt;/strong&gt;: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;when compiler encountering "var a", then ,it asks scope,to see a variable "a" already existed for that particular &lt;strong&gt;scope collection&lt;/strong&gt; .&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If it is already there,the compiler ignores the declaration and moves on.&lt;br&gt;
In this example, the variable is global and not already existed, so the compiler asks &lt;strong&gt;Scope&lt;/strong&gt; to declare a variable in its &lt;strong&gt;Scope collection&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Compiler then produces code for Engine to later execute, to handle the a = 2 assignment. That means &lt;strong&gt;assignment(data=100)&lt;/strong&gt; will be done during execution&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So, the scope of a variable is decided during &lt;strong&gt;compilation time&lt;/strong&gt; and assignment will be done during &lt;strong&gt;execution time&lt;/strong&gt;&lt;/p&gt;


&lt;div class="runkit-element"&gt;
  &lt;code&gt;
    


  &lt;/code&gt;
  &lt;code&gt;
    
var data=100;
return data;

  &lt;/code&gt;
&lt;/div&gt;


&lt;p&gt;The same thing will be happened to a function also. That means the function declaration will be done at a specific scope during compilation and assignment of function definition will be done during execution.&lt;/p&gt;


&lt;div class="runkit-element"&gt;
  &lt;code&gt;
    


  &lt;/code&gt;
  &lt;code&gt;
    
var testFunction=function(){
       return "testFunction called";
}

testFunction();

  &lt;/code&gt;
&lt;/div&gt;


&lt;p&gt;Note: &lt;em&gt;The JS engine compiles your code sometimes during execution,especially when dealing with function execution&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;With this knowledge,let us try the following example.&lt;/p&gt;


&lt;div class="runkit-element"&gt;
  &lt;code&gt;
    


  &lt;/code&gt;
  &lt;code&gt;
    
return a;
var a=100;

  &lt;/code&gt;
&lt;/div&gt;


&lt;p&gt;Here, actually, we expected an error, because we returned the value of variable "a" before it is even declared. But surprisingly, it returned "undefined" which is &lt;em&gt;default value&lt;/em&gt; of a variable.This is because, the &lt;strong&gt;scope&lt;/strong&gt; of variable a is declared during compilation and also initialized with "undefined". That why,it has returned "undefined" instead of error. That means, the variable declaration is "  &lt;em&gt;Hoisted&lt;/em&gt;  ".&lt;/p&gt;

&lt;p&gt;Now let us observe the following&lt;br&gt;
&lt;/p&gt;
&lt;div class="runkit-element"&gt;
  &lt;code&gt;
    

  &lt;/code&gt;
  &lt;code&gt;
    
return a;

  &lt;/code&gt;
&lt;/div&gt;


&lt;p&gt;It has generated "Reference Error" ,because &lt;strong&gt;RHS lookup&lt;/strong&gt; failure.It means,it search for the value of a variable which is not yet declared. So, that variable declaration is not available at its &lt;em&gt;Scope&lt;/em&gt; .&lt;/p&gt;

&lt;p&gt;The same thing would be happened with functions too.&lt;br&gt;
&lt;/p&gt;
&lt;div class="runkit-element"&gt;
  &lt;code&gt;
    


  &lt;/code&gt;
  &lt;code&gt;
    
//calling function before declaration
//but the declaration will be hoisted
testFunction();
 function testFunction(){
      console.log("test function called");
}

  &lt;/code&gt;
&lt;/div&gt;


&lt;p&gt;But when we assign a function to a variable, the that variable will be hoisted and generates &lt;em&gt;Type error&lt;/em&gt;&lt;/p&gt;


&lt;div class="runkit-element"&gt;
  &lt;code&gt;
    


  &lt;/code&gt;
  &lt;code&gt;
    
//calling function before declaration
//but the declaration will be hoisted
testFunction();
 var testFunction=function (){
      console.log("test function called");
}

  &lt;/code&gt;
&lt;/div&gt;


&lt;h2&gt;
  
  
  &lt;strong&gt;Temporal Dead Zone&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Here is the MDN’s explanation of the temporal dead zone:&lt;br&gt;
&lt;em&gt;In ECMAScript 2015, let bindings are not subject to Variable Hoisting, which means that let declarations do not move to the top of the current execution context. Referencing the variable in the block before the initialization results in a ReferenceError (contrary to a variable declared with var, which will just have the undefined value). The variable is in a “temporal dead zone” from the start of the block until the initialization is processed&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;To understand this lengthy statement, first we should know the difference between the old one ,called "var" and the "let" which was introduced in &lt;strong&gt;ES6&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Variables declared by "var" has &lt;em&gt;Function scope&lt;/em&gt; and those declared with "let" has &lt;em&gt;Block scope&lt;/em&gt;&lt;/p&gt;


&lt;div class="runkit-element"&gt;
  &lt;code&gt;
    


  &lt;/code&gt;
  &lt;code&gt;
    
var marks=90;
var testFunction=function(){
       if(marks&amp;gt;80){
       let status="First grade"
       return status;
       }
}

testFunction();

  &lt;/code&gt;
&lt;/div&gt;


&lt;p&gt;Here the variable "marks" is in &lt;em&gt;global scope&lt;/em&gt; which can be known to all functions of that file. But the variable "status" has &lt;em&gt;Block scope&lt;/em&gt; and known only to &lt;em&gt;if block&lt;/em&gt; . When we tried to access "status" from outside of &lt;em&gt;if block&lt;/em&gt;, it generates &lt;em&gt;Refference error&lt;/em&gt;&lt;/p&gt;


&lt;div class="runkit-element"&gt;
  &lt;code&gt;
    


  &lt;/code&gt;
  &lt;code&gt;
    
var marks=90;
var testFunction=function(){
       if(marks&amp;gt;80){
       let status="First grade"
   }

return status;
}

testFunction();

  &lt;/code&gt;
&lt;/div&gt;


&lt;p&gt;Now, let us see about TDZ of "let". Once we revisit the the definition of TDZ,"let bindings are not subject to Variable Hoisting". That means like "var", the variables declared with "let" will not be hoisted. That means no initialization will be done automatically like "var" with "undefined".&lt;/p&gt;


&lt;div class="runkit-element"&gt;
  &lt;code&gt;
    


  &lt;/code&gt;
  &lt;code&gt;
    
let a=100;
return a;

  &lt;/code&gt;
&lt;/div&gt;


&lt;p&gt;But, because of TDZ, the variables declared with "let" will not be initialized. Because of this fact, when we try to access then before their initialization we will get &lt;em&gt;Reference error&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="runkit-element"&gt;
  &lt;code&gt;
    


  &lt;/code&gt;
  &lt;code&gt;
    
return a;
let a=100;


  &lt;/code&gt;
&lt;/div&gt;


&lt;p&gt;Hope this brief discussion helped you to understand the basics in clear way.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Understanding async and await in JavaScript</title>
      <dc:creator>Rajesh T</dc:creator>
      <pubDate>Sun, 10 May 2020 08:49:46 +0000</pubDate>
      <link>https://forem.com/rajesh04159786/understanding-async-and-await-in-javascript-63o</link>
      <guid>https://forem.com/rajesh04159786/understanding-async-and-await-in-javascript-63o</guid>
      <description>&lt;p&gt;Before reading this article one should have good understanding of callbacks,Promises of JavaScript.&lt;br&gt;
  If you not ware of them still,i recommend you to go through my articles&lt;br&gt;
  &lt;a href="https://dev.to/rajesh04159786/callbacks-in-javascript-5210"&gt;callbacks&lt;/a&gt; &lt;br&gt;
  &lt;a href="https://dev.to/rajesh04159786/understanding-javascript-promises-pkh"&gt;Promises&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let us see the definition of async and await from documentation&lt;/p&gt;

&lt;p&gt;"An async function is a function declared with the async keyword. Async functions are instances of the AsyncFunction constructor, and the await keyword is permitted within them. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains"&lt;/p&gt;

&lt;p&gt;That means async and await are developed based on promises. One can write code to work asynchronously using async and await very easily and code is in very clean format.&lt;/p&gt;
&lt;h2&gt;
  
  
  async
&lt;/h2&gt;

&lt;p&gt;Let us understand async first.&lt;br&gt;
Consider the following function.&lt;br&gt;
&lt;/p&gt;
&lt;div class="runkit-element"&gt;
  &lt;code&gt;
    


  &lt;/code&gt;
  &lt;code&gt;
    
async function test(){

}
console.log(test())


  &lt;/code&gt;
&lt;/div&gt;


&lt;p&gt;It returns a Promise object whose status is "resolved" and value is "undefined".&lt;br&gt;
That means an async function returns promise.&lt;/p&gt;

&lt;p&gt;Let us return some value by this function&lt;br&gt;
&lt;/p&gt;
&lt;div class="runkit-element"&gt;
  &lt;code&gt;
    


  &lt;/code&gt;
  &lt;code&gt;
    
async function test(){
       return 100;
}
test().then((value)=&amp;gt;value)


  &lt;/code&gt;
&lt;/div&gt;
&lt;br&gt;
 Now the value of promise object is 100.

&lt;p&gt;It is same as explicitly returning promise like below&lt;/p&gt;


&lt;div class="runkit-element"&gt;
  &lt;code&gt;
    


  &lt;/code&gt;
  &lt;code&gt;
    
async function test(){
       return Promise.resolve(100);
}
test().then((value)=&amp;gt;value)


  &lt;/code&gt;
&lt;/div&gt;


&lt;p&gt;Now, we are very clear about await function.Let us focus on async.&lt;/p&gt;

&lt;h2&gt;
  
  
  await
&lt;/h2&gt;

&lt;p&gt;"Async functions can contain zero or more await expressions. Await expressions suspend progress through an async function, yielding control and subsequently resuming progress only when an awaited promise-based asynchronous operation is either fulfilled or rejected"&lt;br&gt;
That means "an await expression" suspends progress until the async function of that expression completes its execution.&lt;br&gt;
syntax:&lt;br&gt;
&lt;strong&gt;let value=await promise;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Let us understand this with an example&lt;br&gt;
&lt;/p&gt;
&lt;div class="runkit-element"&gt;
  &lt;code&gt;
    


  &lt;/code&gt;
  &lt;code&gt;
    
function waitForTaskStatus(){
   return new Promise((resolve,reject)=&amp;gt;{
    setTimeout(() =&amp;gt; {
        resolve("task completed")
    }, 2000);
   })
}

async function test(){
    console.log("waiting for task status")
    let status=await waitForTaskStatus();
    return status;
}
test();


  &lt;/code&gt;
&lt;/div&gt;


&lt;p&gt;We just experienced asynchronous nature of  await expression which suspends the progress until the "waitForTaskStats()" function is executed.Then only the rest of statements of "test() function" will get chance to execute.&lt;/p&gt;

&lt;p&gt;By using "await" ,we can avoid calling "then()" on promise object to deal with its resolve status.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The await keyword is only valid inside async functions. If you use it outside of an async function's body, you will get a SyntaxError.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The purpose of async/await is to simplify the syntax necessary to consume promise-based APIs. The behavior of async/await is similar to combining generators and promises.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Now let us implement the use what i considered in my &lt;br&gt;
&lt;a href="https://dev.to/rajesh04159786/callbacks-in-javascript-5210"&gt;article on callbackscallbacks&lt;/a&gt; ,&lt;br&gt;
  &lt;a href="https://dev.to/rajesh04159786/understanding-javascript-promises-pkh"&gt;article on Promises&lt;/a&gt;&lt;br&gt;
which is " &lt;em&gt;find big number of given two numbers,add 100 to to it and subtract 10 from the result&lt;/em&gt; ". Let us implement the same using async and await.&lt;/p&gt;


&lt;div class="runkit-element"&gt;
  &lt;code&gt;
    


  &lt;/code&gt;
  &lt;code&gt;
    
function finBig(first,second){
    return new Promise((res)=&amp;gt;{
        setTimeout(() =&amp;gt; {
            if(first&amp;gt;second|| first==second){
                console.log("big number is ",first);
                res(first);
            }
            else{
                console.log("big number is ",second);
                res(second);
            }
        }, 2000);


});

}

function incrementResultBy100(bigNumber){
    return new Promise((res)=&amp;gt;{
        let bigNUmberAddedBy100=bigNumber+100;
        console.log("big number after added with 100 is  is ",bigNUmberAddedBy100);
        res(bigNUmberAddedBy100);

    }
)}

function decreaseResultBy10(bigNUmberAddedBy100)
{
    return new Promise((res)=&amp;gt;{
        setTimeout(() =&amp;gt; {
            let result=bigNUmberAddedBy100-10;
          //  console.log("result after decrement of 10 is  is ",result);
             res(result);
        }, 1000);


});

}

function test(){
return finBig(100,200).then((bigNumber)=&amp;gt;{
return incrementResultBy100(bigNumber)

}).then((bigNUmberAddedBy100)=&amp;gt;{
return decreaseResultBy10(bigNUmberAddedBy100);

}).then(result=&amp;gt;{
console.log("final result  after decreasing 10 is ",result)

}).catch((err)=&amp;gt;{console.log("err is ",err)});

}

test();


  &lt;/code&gt;
&lt;/div&gt;


&lt;p&gt;Now, let us rewrite the above using async and await which can be more clean like below&lt;/p&gt;


&lt;div class="runkit-element"&gt;
  &lt;code&gt;
    


  &lt;/code&gt;
  &lt;code&gt;
    
function finBig(first,second){
    return new Promise((res)=&amp;gt;{
        setTimeout(() =&amp;gt; {
            if(first&amp;gt;second|| first==second){
                console.log("big numbe is ",first);
                res(first);
            }
            else{
                console.log("big numbe is ",second);
                res(second);
            }
        }, 2000);


});

}

function incrementResultBy100(bigNumber){
    return new Promise((res)=&amp;gt;{
        let bigNUmberAddedBy100=bigNumber+100;
        console.log("big number after added with 100 is  is ",bigNUmberAddedBy100);
        res(bigNUmberAddedBy100);

    }
)}

function decreaseResultBy10(bigNUmberAddedBy100)
{
    return new Promise((res)=&amp;gt;{
        setTimeout(() =&amp;gt; {
            let result=bigNUmberAddedBy100-10;
          //  
             res(result);
        }, 1000);


});

}

async function test(){
    try{
    const bigNumber=await finBig(1000,200);
    const bigNUmberAddedBy100=await incrementResultBy100(bigNumber);
    const result=await decreaseResultBy10(bigNUmberAddedBy100);
    console.log("result after decrement of 10 is  is ",result);
    }
    catch(err){
        console.log("err is ",err)
    }
}

test()


  &lt;/code&gt;
&lt;/div&gt;


&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;The async keyword before a function has two effects:&lt;/p&gt;

&lt;p&gt;Makes it always return a promise.&lt;br&gt;
Allows await to be used in it.&lt;br&gt;
The await keyword before a promise makes JavaScript wait until that promise settles, and then:&lt;/p&gt;

&lt;p&gt;If it’s an error, the exception is generated — same as if throw error were called at that very place.&lt;br&gt;
Otherwise, it returns the result.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>async</category>
      <category>await</category>
      <category>promise</category>
    </item>
    <item>
      <title>Understanding JavaScript promises</title>
      <dc:creator>Rajesh T</dc:creator>
      <pubDate>Thu, 07 May 2020 18:12:32 +0000</pubDate>
      <link>https://forem.com/rajesh04159786/understanding-javascript-promises-pkh</link>
      <guid>https://forem.com/rajesh04159786/understanding-javascript-promises-pkh</guid>
      <description>&lt;p&gt;&lt;a href="https://www.linkedin.com/pulse/promises-javascript-rajesh-t/"&gt;https://www.linkedin.com/pulse/promises-javascript-rajesh-t/&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Callbacks in JavaScript</title>
      <dc:creator>Rajesh T</dc:creator>
      <pubDate>Wed, 06 May 2020 14:35:51 +0000</pubDate>
      <link>https://forem.com/rajesh04159786/callbacks-in-javascript-5210</link>
      <guid>https://forem.com/rajesh04159786/callbacks-in-javascript-5210</guid>
      <description>&lt;p&gt;Most of us  feel confusion  while learning about asynchronous behavior of JavaScript. In this article i tried to explain need and nature of callbacks with simple examples. &lt;/p&gt;

&lt;p&gt;JavaScript is a single threaded language. This means it has one call stack and one memory heap. As expected, it executes code in order and must finish executing a piece code before moving onto the next.&lt;/p&gt;

&lt;p&gt;Let us understand the above statement with a very simple example. Let us take a use case as " Find big number in given two numbers and then add 10 to that big number". It is very simple example which can help us to understand asynchronous behavior of JavaScript.&lt;/p&gt;

&lt;p&gt;The above use case has two tasks. One is finding big number and second one is adding  10 to the result of first task.&lt;/p&gt;

&lt;p&gt;Let me take two functions to implement above two tasks.&lt;/p&gt;

&lt;p&gt;var bigNumber;&lt;br&gt;
//function to find big number&lt;br&gt;
function findBig(firstNumber,secondNumber)&lt;br&gt;
{&lt;br&gt;
    if(firstNumber&amp;gt;secondNumber){ &lt;br&gt;
        bigNumber=firstNumber;&lt;br&gt;&lt;br&gt;
    }&lt;br&gt;&lt;br&gt;
    else if(firstNumber==secondNumber){ &lt;br&gt;
        bigNumber=firstNumber;&lt;br&gt;&lt;br&gt;
    }&lt;br&gt;
    else{&lt;br&gt;
        bigNumber=secondNumber;&lt;br&gt;
    }&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;//function to add 10 to big number&lt;br&gt;
function incrementResultBy10(){&lt;br&gt;
    let result=bigNumber+10;&lt;br&gt;
    console.log("big number is ",bigNumber);&lt;br&gt;
    console.log("result after increment is ",result);&lt;br&gt;
 }&lt;/p&gt;

&lt;p&gt;//call functions&lt;/p&gt;

&lt;p&gt;findBig(100,200);&lt;br&gt;
 incrementResultBy10();&lt;/p&gt;

&lt;p&gt;we will get output as&lt;/p&gt;

&lt;p&gt;big number is 100&lt;/p&gt;

&lt;p&gt;result after increment is 110&lt;/p&gt;

&lt;p&gt;Everything  is as we expected and nothing to confuse.  Great....&lt;/p&gt;

&lt;p&gt;Now, let us assume as it may take some time to find and to return big number. It is not really happened here.  All I/O operations are blocking operations.But to understand callbacks with simple example,let us make this assumption. For this we can use&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;                      setTimeout(()=&amp;gt;{},timeout) 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;var bigNumber;&lt;/p&gt;

&lt;p&gt;//function to find big number&lt;/p&gt;

&lt;p&gt;function findBig(firstNumber,secondNumber)&lt;/p&gt;

&lt;p&gt;{&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if(firstNumber&amp;gt;secondNumber){

  setTimeout(() =&amp;gt; {

              bigNumber=firstNumber;  

  }, 1000);                     

}   

else if(firstNumber==secondNumber){       

    setTimeout(() =&amp;gt; {

        bigNumber=firstNumber;      

      }, 1000);        

}

else{

    setTimeout(() =&amp;gt; {

        bigNumber=secondNumber;      

      }, 1000); 

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;//function to add 10 to big number&lt;/p&gt;

&lt;p&gt;function incrementResultBy10(){&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let result=bigNumber+10;

console.log("big number is ",bigNumber)

console.log("result after increment is ",result);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;//call functions&lt;/p&gt;

&lt;p&gt;findBig(200,200);&lt;/p&gt;

&lt;p&gt;incrementResultBy10();&lt;/p&gt;

&lt;p&gt;Now, surprisingly we got output as &lt;/p&gt;

&lt;p&gt;big number is undefined&lt;/p&gt;

&lt;p&gt;result after increment is NaN&lt;/p&gt;

&lt;p&gt;Why??????&lt;br&gt;
What is happening behind ?????&lt;/p&gt;

&lt;p&gt;Let us focus on understanding this behavior. As we knew JavaScript is single threaded, with one call stack, it will take support of WebAPI to execute things asynchronously. That means, In this example, the function call( findBig(200,200)) will start execution. Inside of it,setTimeout() method  is existed. Then JavaScript will forward that to WebAPI and meanwhile, It will execute the second function call(incrementResultBy10()). Then this function will execute  before the first function  completes its timeout. That's why we got such result where variable bigNumber is not assigned with actual value until the first function completes its execution.&lt;/p&gt;

&lt;p&gt;Let us fix this issue &lt;br&gt;
The solution to this problem is , the second function (incrementResultBy10()) should wait until the first function call(findBig(200,200)) is  completed. But how to control flow of execution as per our need. Callbacks are introduced to solve these kind of problems.&lt;/p&gt;

&lt;p&gt;Callback function&lt;br&gt;
Callback function is an argument to another function,which will be executed eventually ,when outside function completes its execution.&lt;/p&gt;

&lt;p&gt;This can help us to fix the above issue. Now let us refine the findBig(firstNumber,secondNumber) using callback function like below.&lt;/p&gt;

&lt;p&gt;function findBig ( firstNumber , secondNumber , callback)&lt;/p&gt;

&lt;p&gt;{&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if(firstNumber&amp;gt;secondNumber){

    setTimeout(() =&amp;gt; {

        callback(firstNumber);  

    }, 2000);      

}   

else if(firstNumber==secondNumber){       

    setTimeout(() =&amp;gt; {

        callback(firstNumber);  

    }, 2000);       

}

else{

    setTimeout(() =&amp;gt; {

        callback(secondNumber);  

    }, 2000);

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;Now the third parameter is "callback" which can receive a function as argument and execute  after timeout.Now let us efine second task which can add 10 to big number like below.&lt;/p&gt;

&lt;p&gt;function incrementResultBy10(bigNumber){&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let result=bigNumber+10;

console.log("big number is ",bigNumber)

console.log("result after increment is ",result)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;Then pass this function as third argument to findBig() function.&lt;/p&gt;

&lt;p&gt;findBig(200,1000,incrementResultBy10)&lt;/p&gt;

&lt;p&gt;Now , the second function can be executed only after the completion of findBig() function.Hence the issue is resolved. &lt;/p&gt;

&lt;p&gt;Hope you understand the need and behavior of callbacks in JavaScript. With this understanding, we can use callbacks to deal with blocking I/O operations.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Error handling in Express Applicatopn</title>
      <dc:creator>Rajesh T</dc:creator>
      <pubDate>Sat, 02 May 2020 06:13:24 +0000</pubDate>
      <link>https://forem.com/rajesh04159786/error-handling-in-express-applicatopn-44d4</link>
      <guid>https://forem.com/rajesh04159786/error-handling-in-express-applicatopn-44d4</guid>
      <description>&lt;p&gt;&lt;a href="https://www.linkedin.com/pulse/error-handling-express-application-rajesh-t"&gt;https://www.linkedin.com/pulse/error-handling-express-application-rajesh-t&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Storing images in MEAN stack application using "Cloudinary"</title>
      <dc:creator>Rajesh T</dc:creator>
      <pubDate>Sat, 02 May 2020 06:12:22 +0000</pubDate>
      <link>https://forem.com/rajesh04159786/storing-images-in-mean-stack-application-using-cloudinary-2pd1</link>
      <guid>https://forem.com/rajesh04159786/storing-images-in-mean-stack-application-using-cloudinary-2pd1</guid>
      <description>&lt;p&gt;Saving images and videos of a web application is always challenging, because, performance of application matters.We have 2 options to deal with this&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Storing images in database&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Storing images in cloud&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In this article ,i will explain how to store images and videos in "Cloudinary"&lt;/p&gt;

&lt;p&gt;Cloudinary&lt;br&gt;
Cloudinary is a cloud-based service that provides an end-to-end image and video management solution. The Node.js SDK provides simple, yet comprehensive image and video manipulation, optimization, and delivery capabilities that you can implement using code that integrates seamlessly with your existing Node.js SDK application.&lt;/p&gt;

&lt;p&gt;The following diagrams explains the process of saving User data into database collection.&lt;/p&gt;

&lt;p&gt;No alt text provided for this image&lt;br&gt;
It contains 4 steps.&lt;/p&gt;

&lt;p&gt;Step-1: Sending user data along with profile image to server by making HTTP POST request&lt;/p&gt;

&lt;p&gt;Step-2: Image(or video i.e. a file) of request object can save to cloudinary storage.&lt;/p&gt;

&lt;p&gt;Step-3 : Once the file is stored to cloudinary, it returns CDN link of the image&lt;/p&gt;

&lt;p&gt;Step-4 : Add the CDN link of profile picture to user data and save it to Database(user collection)&lt;/p&gt;

&lt;p&gt;Step-1-Sending user data along with profile image to server by making HTTP POST request&lt;br&gt;
Create register component and register service in Angular application. Then, add registration form to register component.&lt;/p&gt;

&lt;h2&gt;
  
  
  register.component.html
&lt;/h2&gt;


&lt;br&gt;
    &amp;lt;!--name--&amp;gt;&lt;br&gt;
   &lt;br&gt;
          Name&lt;br&gt;
          
                                     class="form-control" ngModel&amp;gt;&lt;br&gt;
    
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  &amp;lt;!--username--&amp;gt;

 &amp;lt;div class="form-group"&amp;gt;

 &amp;lt;label for="un"&amp;gt;Username&amp;lt;/label&amp;gt;

 &amp;lt;input type="text" id="un" name="username" class="form-control" ngModel&amp;gt;

 &amp;lt;/div&amp;gt;


        &amp;lt;!--password--&amp;gt;

 &amp;lt;div class="form-group"&amp;gt;

  &amp;lt;label for="pw"&amp;gt;Password&amp;lt;/label&amp;gt;

 &amp;lt;input type="text" id="pw" name="password" class="form-control" ngModel&amp;gt;

 &amp;lt;/div&amp;gt;




          &amp;lt;!--email--&amp;gt;
&lt;/code&gt;&lt;/pre&gt;


&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;label for="em"&amp;gt;Email&amp;lt;/label&amp;gt;

&amp;lt;input type="email" id="em" name="email" class="form-control" ngModel&amp;gt;
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;&amp;lt;!--date of birth--&amp;gt;&lt;/p&gt;



&lt;pre class="highlight plaintext"&gt;&lt;code&gt; &amp;lt;label for="db"&amp;gt;Email&amp;lt;/label&amp;gt;

 &amp;lt;input type="date" id="db" name="dob" class="form-control" ngModel&amp;gt;
&lt;/code&gt;&lt;/pre&gt;



&lt;p&gt;&amp;lt;!--profile image--&amp;gt;&lt;/p&gt;

&lt;p&gt;Choose profile image&lt;/p&gt;

&lt;p&gt;&lt;a href="" class="article-body-image-wrapper"&gt;&lt;img&gt;&lt;/a&gt;&lt;/p&gt;



&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    &amp;lt;button type="submit" class="btn btn-success"&amp;gt;Register&amp;lt;/button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;





&lt;h2&gt;
  
  
  register.component.ts
&lt;/h2&gt;

&lt;p&gt;import { Component, OnInit } from '@angular/core';&lt;br&gt;
import { NgForm } from '@angular/forms';&lt;br&gt;
import { RegisterService } from '../register.service';&lt;br&gt;
import { Router } from '@angular/router';&lt;/p&gt;

&lt;p&gt;@Component({&lt;br&gt;
  selector: 'app-register',&lt;br&gt;
  templateUrl: './register.component.html',&lt;br&gt;
  styleUrls: ['./register.component.css']&lt;br&gt;
})&lt;br&gt;
export class RegisterComponent implements OnInit {&lt;/p&gt;

&lt;p&gt;//inject register service obj&lt;br&gt;
  constructor(private rs:RegisterService,private router:Router) { }&lt;/p&gt;

&lt;p&gt;ngOnInit(): void {&lt;br&gt;
  }&lt;/p&gt;

&lt;p&gt;file: File;&lt;/p&gt;

&lt;p&gt;imageUrl: string | ArrayBuffer ="&lt;a href="https://bulma.io/images/placeholders/480x480.png"&gt;https://bulma.io/images/placeholders/480x480.png&lt;/a&gt;";&lt;/p&gt;

&lt;p&gt;fileName: string = "No file selected";&lt;/p&gt;

&lt;p&gt;//this method receives file content ,read and make it ready for preview&lt;/p&gt;

&lt;p&gt;onChange(file: File) {&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (file) {
  this.fileName = file.name;
  this.file = file;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;/*The FileReader object lets web applications asynchronously      read the contents of files (or raw data buffers) stored on the user's computer,&lt;br&gt;
 using File or Blob objects to specify the file or data to read. */&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  const reader = new FileReader();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;//The readAsDataURL method is used to read the contents of the specified Blob or File&lt;br&gt;
      reader.readAsDataURL(file);&lt;/p&gt;

&lt;p&gt;/&lt;em&gt;A handler for the load event. This event is triggered &lt;br&gt;
  each time the reading operation is successfully completed.&lt;br&gt;
  The FileReader.onload property contains an event handler&lt;br&gt;
   executed when the load event is fired&lt;/em&gt;/&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  reader.onload = () =&amp;gt; {
    /*  the "result" attribute contains the data as a base64 encoded string.*/

    this.imageUrl = reader.result;

  };
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;//this methid is called at form submission&lt;br&gt;
  submit(formObj:NgForm)&lt;br&gt;
  {&lt;br&gt;
    //formdata obj preperation&lt;br&gt;
    let formData=new FormData();&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//get user object from NgForm object
let userObj=formObj.value;

  //append image to it
  formData.append("photo",this.file);

 //append user object by converting it into string
  formData.append("userObj",JSON.stringify(userObj));


 //pass "formData" object to register service to make HTTP POST request 
  this.rs.doRegister(formData).subscribe((result)=&amp;gt;{

      if( result["message"]=="user existed")
       {
         alert("user already existed");
         formObj.reset();
       }
     if( result["message"]=="user created")
       {
         alert("user created successfully");
         //redirect to login page
         this.router.navigate(['./login']);
       }
  })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;}&lt;/p&gt;

&lt;h2&gt;
  
  
  register.service.ts
&lt;/h2&gt;

&lt;p&gt;import { Injectable } from '@angular/core';&lt;br&gt;
import { HttpClient } from '@angular/common/http';&lt;br&gt;
import { Observable } from 'rxjs';&lt;/p&gt;

&lt;p&gt;@Injectable({&lt;br&gt;
  providedIn: 'root'&lt;br&gt;
})&lt;br&gt;
export class RegisterService {&lt;/p&gt;

&lt;p&gt;constructor(private hc:HttpClient) { }&lt;/p&gt;

&lt;p&gt;doRegister(userObj):Observable&lt;br&gt;
  {&lt;br&gt;
    //make http post req and returns Observable&lt;br&gt;
    return  this.hc.post('/user/register',userObj);&lt;/p&gt;

&lt;p&gt;}&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;Step-2: Image(or video i.e. a file) of request object can save to cloudinary storage.&lt;br&gt;
Once the FormData object is reached to server.js, it will execute "userApi.js" by sending request object to it.&lt;/p&gt;

&lt;h2&gt;
  
  
  server.js
&lt;/h2&gt;

&lt;p&gt;//load express function&lt;br&gt;
const exp=require("express");&lt;br&gt;
//create express obj&lt;br&gt;
const app=exp();&lt;/p&gt;

&lt;p&gt;const path=require("path");&lt;/p&gt;

&lt;p&gt;//connecting ANgular app with this server&lt;br&gt;
app.use(exp.static(path.join(__dirname,'./dist/AngApp9WithMultipleModules')));&lt;/p&gt;

&lt;p&gt;//import MongoClient&lt;br&gt;
const mc=require("mongodb").MongoClient;&lt;/p&gt;

&lt;p&gt;//import  user router&lt;/p&gt;

&lt;p&gt;const userApiObj=require("./apis/userApi");&lt;/p&gt;

&lt;p&gt;//if path contains '/user'&lt;br&gt;
app.use('/user',userApiObj);&lt;br&gt;
;&lt;/p&gt;

&lt;p&gt;//middleware to handle unavailable paths&lt;br&gt;
app.use((req,res,next)=&amp;gt;{&lt;br&gt;
    res.send({message:&lt;code&gt;path ${req.url} is not available&lt;/code&gt;});&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;//get db url from mongo atlas&lt;br&gt;
var dbUrl = "mongodb+srv://b26:&lt;a href="mailto:b26@cluster0-z3col.mongodb.net"&gt;b26@cluster0-z3col.mongodb.net&lt;/a&gt;/test?retryWrites=true&amp;amp;w=majority";&lt;/p&gt;

&lt;p&gt;mc.connect(dbUrl,{useNewUrlParser:true,useUnifiedTopology:true},(err,client)=&amp;gt;{&lt;br&gt;
    if(err)&lt;br&gt;
    {&lt;br&gt;
        console.log("Err in db connect ",err);&lt;br&gt;
    }&lt;br&gt;
    else{&lt;br&gt;
        //get db connection object&lt;br&gt;
        let b26DatabaseObject=client.db("b26db");&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    //get collection objects
    let userCollectionObj=b26DatabaseObject.collection("usercollection");
    let adminCollectionObj=b26DatabaseObject.collection("admincollection");


    console.log("db connected..");



    //assign collection objects to "locals" object of "app"
    app.locals.userCollectionObj=userCollectionObj;
    app.locals.adminCollectionObj=adminCollectionObj;



    const port=4000;
    app.listen(port,()=&amp;gt;{ console.log(`server listening on port ${port}`)});


}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;});&lt;/p&gt;

&lt;p&gt;Now, we need to configure the cloudinary service.For that, register and login into &lt;a href="https://cloudinary.com/"&gt;https://cloudinary.com/&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Then it will provide crdentials to use its API and they are "Cloud name","API Key" and "API secret".&lt;/p&gt;

&lt;p&gt;Now install and import the following modules at userApi.js&lt;/p&gt;

&lt;p&gt;cloudinary&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;                                           multer-storage-cloudinary

                                           multer
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;const cloudinary = require("cloudinary");&lt;/p&gt;

&lt;p&gt;const cloudinaryStorage = require("multer-storage-cloudinary");&lt;/p&gt;

&lt;p&gt;const multer = require("multer");&lt;/p&gt;

&lt;p&gt;Now configure cloudinary with its credentials.&lt;/p&gt;

&lt;p&gt;cloudinary.config({&lt;/p&gt;

&lt;p&gt;cloud_name: "xxxxxxx",&lt;/p&gt;

&lt;p&gt;api_key: "xxxxxx",&lt;/p&gt;

&lt;p&gt;api_secret: "xxxxxxx",&lt;/p&gt;

&lt;p&gt;});&lt;/p&gt;

&lt;p&gt;Now, after configuring cloudinary, configure storage at cloudinary.&lt;/p&gt;

&lt;p&gt;var storage = cloudinaryStorage({&lt;/p&gt;

&lt;p&gt;cloudinary: cloudinary,&lt;/p&gt;

&lt;p&gt;folder: "user-profiles",&lt;/p&gt;

&lt;p&gt;allowedFormats: ["jpg", "png"],&lt;/p&gt;

&lt;p&gt;filename: function (req, file, cb) {&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; cb(undefined, file.fieldname + "-" + Date.now());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;},&lt;/p&gt;

&lt;p&gt;});&lt;/p&gt;

&lt;p&gt;Now,configure multer middleware&lt;/p&gt;

&lt;p&gt;var upload = multer({ storage: storage });&lt;/p&gt;

&lt;p&gt;Then it will use configured storage location at cloudinary to store file data&lt;/p&gt;

&lt;p&gt;Step-3 : Once the file is stored to cloudinary, it returns CDN link of the image&lt;br&gt;
Execute multer middleware before request handling middleware by adding it as second argumant like below.&lt;/p&gt;

&lt;p&gt;the method "single(string)" will upload single image to storage location.&lt;/p&gt;

&lt;p&gt;const exp = require("express");&lt;br&gt;
 const userRouter = exp.Router();&lt;/p&gt;

&lt;p&gt;//use body parser middleware&lt;br&gt;
userRouter.use(exp.json());&lt;/p&gt;

&lt;p&gt;userRouter.post("/register", upload.single("photo"), (req, res, next) =&amp;gt; {&lt;/p&gt;

&lt;p&gt;console.log("req body is ",req.body)&lt;/p&gt;

&lt;p&gt;/&lt;em&gt;multer middleware will execute first before req handling middleware&lt;br&gt;
    save image to cloudinary and get CDN link in req.file.secure_url property&lt;/em&gt;/&lt;/p&gt;

&lt;p&gt;console.log("url is ", req.file.secure_url);&lt;br&gt;
   console.log("user data is ", JSON.parse(req.body.userObj));&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//now parse userObj and assign to req.body

req.body=JSON.parse(req.body.userObj); 


//add CDN link of profile image to req.body


req.body.profileImageUrl= req.file.secure_url;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;// write user create logic here..............................&lt;/p&gt;

&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;Step-4 : Add the CDN link of profile picture to user data and save it to Database(user collection)&lt;br&gt;
The following Code contains user registration logic&lt;/p&gt;

&lt;p&gt;userRouter.post("/register", upload.single("photo"), (req, res, next) =&amp;gt; {&lt;/p&gt;

&lt;p&gt;console.log("req body is ",req.body)&lt;br&gt;
  console.log("url is ", req.file.secure_url);&lt;br&gt;
  console.log("user data is ", JSON.parse(req.body.userObj));&lt;/p&gt;

&lt;p&gt;req.body=JSON.parse(req.body.userObj);&lt;br&gt;&lt;br&gt;
  req.body.imgUrl = req.file.secure_url;&lt;/p&gt;

&lt;p&gt;delete req.body.photo;&lt;/p&gt;

&lt;p&gt;//get usercollection object from "req.app.locals" object&lt;br&gt;
  let userCollectionObj = req.app.locals.userCollectionObj;&lt;/p&gt;

&lt;p&gt;//check for a user in user collection with the "username" received from client&lt;br&gt;
  userCollectionObj.findOne({ username: req.body.username }, (err, userObj) =&amp;gt; {&lt;br&gt;
    if (err) {&lt;br&gt;
      next(err);&lt;br&gt;
    }&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//if user is existed
if (userObj != null) {
  res.send({
    message: "user existed",
  });
}

//if user is not existed

else {
  //insert "req.body" into usercollection

  //hash the password
  bcrypt.hash(req.body.password, 7, (err, hashedPassword) =&amp;gt; {
    if (err) {
      next(err);
    }


    //replace paint text password with hashedpassword
    req.body.password = hashedPassword;


    //insert req.body to user collection
    userCollectionObj.insertOne(req.body, (err, success) =&amp;gt; {
      if (err) {
        next(err);
      }
      res.send({ message: "user created" });
    });
  });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;});&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;Now the user collection of database contains user object will all user data along with CDN link of his profile image.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Storing images in MEAN stack application using "Cloudinary"</title>
      <dc:creator>Rajesh T</dc:creator>
      <pubDate>Mon, 27 Apr 2020 07:04:08 +0000</pubDate>
      <link>https://forem.com/rajesh04159786/storing-images-in-mean-stack-application-using-cloudinary-4c21</link>
      <guid>https://forem.com/rajesh04159786/storing-images-in-mean-stack-application-using-cloudinary-4c21</guid>
      <description>&lt;p&gt;&lt;a href="https://www.linkedin.com/pulse/storing-images-mean-stack-application-using-cloudinary-rajesh-t/"&gt;https://www.linkedin.com/pulse/storing-images-mean-stack-application-using-cloudinary-rajesh-t/&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Connecting Angular application with Nodejs backend</title>
      <dc:creator>Rajesh T</dc:creator>
      <pubDate>Sat, 25 Apr 2020 14:40:35 +0000</pubDate>
      <link>https://forem.com/rajesh04159786/connecting-angular-application-with-nodejs-backend-1l81</link>
      <guid>https://forem.com/rajesh04159786/connecting-angular-application-with-nodejs-backend-1l81</guid>
      <description>&lt;p&gt;In this article, i will explain ,how to connect Angular Application with Nodejs backend.&lt;/p&gt;

&lt;p&gt;When we create a new angular application using CLI tool, we will be provided with live development server to run that application. It will listen to port number 4200 by default.&lt;/p&gt;

&lt;p&gt;When we send request to live development server from browser as &lt;a href="http://127.0.0.1:4200"&gt;http://127.0.0.1:4200&lt;/a&gt; then it will send the JavaScript bundles of Angular application as response.That server is enough to run and test angular application.&lt;/p&gt;

&lt;p&gt;When we implement server side services,we can use web server/HTTP server like Apache tomcat. But when we use NodeJS as backend technology,it allows to create HTTP server instead of using third party web servers.&lt;/p&gt;

&lt;p&gt;Creating HTTP server in NodeJS&lt;br&gt;
We can use either "http" module or "express" module to create a HTTP Server .Express is a web application framework which run on top of NodeJS. It is combination of multiple middlewares which can help developer to create efficient server side services of a web application.Let us create an HTTP server using "express" module.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;          //load express module                               
                  const express=require("express");


          //call function loaded to "express" variable to get express object
                   const app=express();


          //assign port number
                app.listen(3000,()=&amp;gt; {
                                 console.log("server starting on port 3000");
                                     }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now ,save it as "server.js" and can start the server by running following command.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;                         node server.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now, once the HTTP server is ready ,then we can focus on connecting Angular application with this server. We know that Angular is written in TypeScript .SO first we need to create JavaScript bundles by transpiling the Angular app.&lt;/p&gt;

&lt;p&gt;The ng serve command is intentionally for fast, local and iterative developments and also for builds, watches and serves the application from a local CLI development server.&lt;/p&gt;

&lt;p&gt;The ng build command is intentionally for building the apps and deploying the build artifacts. It is also possible to run this command in watch mode as "ng build --watch" which can rebuild the angular app automatically after modifications.&lt;/p&gt;

&lt;p&gt;When we run "ng build" command,then it will create a folder "dist" at root level of application and a sub folder in it with the same name of application.In side of that sub folder it places JavaScript bundles of Angular application. One can find reason for "dist" folder creation in "angular.json" file.&lt;/p&gt;

&lt;p&gt;"options": {&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;         "outputPath": "dist/&amp;lt;name-of-application&amp;gt;",
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;......................................................&lt;/p&gt;

&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;Now it is the time to connect the content of " dist " folder with HTTP server that we created using "express" module above.&lt;/p&gt;

&lt;p&gt;In express module, a method called static() is existed to serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.The function signature is&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;                      express.static(root, [options])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The root argument specifies the root directory from which to serve static assets.Now, we need to join the paths of server and "dist" folder which contains static content as JavaScript bundles. For this ,we use core module of NodeJS called "path". This module has method to join the paths.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;           express.static(path.join( __dirname,'./dist/&amp;lt;Sub-folder-name&amp;gt;));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;"__dirname" is the directory name of the current module( i.e. server.js).&lt;/p&gt;

&lt;p&gt;Now ,inform to express application to use this.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  app.use (express.static(path.join( __dirname,'./dist/&amp;lt;Sub-folder-name&amp;gt;)));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Hence the Angular app is connected with Nodejs backend. Now start the HTTP server and make a request from browser as&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;                      http://127.0.0.1:3000
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now the HTTP server will send the "JavaScript bundles" of angular app as response to client.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Token based Authentication in ExpressJS Application</title>
      <dc:creator>Rajesh T</dc:creator>
      <pubDate>Fri, 24 Apr 2020 07:15:55 +0000</pubDate>
      <link>https://forem.com/rajesh04159786/token-based-authentication-in-expressjs-application-14fk</link>
      <guid>https://forem.com/rajesh04159786/token-based-authentication-in-expressjs-application-14fk</guid>
      <description>&lt;p&gt;HTTP is a stateless protocol. That means ,it cannot maintain state of previous requests. A web application can contain some un-protected routes and some protected routes. The Un-protected routes can be accessed by any user. But protected routes can be accessed only by Authorized users.&lt;br&gt;
A user can prove his authorization by submitting his credentials (username and password) for every request he makes which is practically panic. Once the server receives the user credentials, It should check   with “user data” in database for correctness of user credentials. This is another nightmare which can degrade the application’s efficiency.&lt;br&gt;
To overcome this problem, the concept of authentication is introduced. It works like below.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;When the user submits his credentials ,then the server will verify them.&lt;br&gt;
a.  If username is not matched,Then it will send “invalid username” to client&lt;br&gt;
b.  If password is not matched,then it will send “invalid password” to client&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If username and password are matched, then the server has to create either SessionID or JWT token with respect to that user and can send it as response.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;(Note: You can find difference between Session based authentication and Token based authentication at &lt;br&gt;
 &lt;a href="https://medium.com/@sherryhsu/session-vs-token-based-authentication-11a6c5ac45e4"&gt;https://medium.com/@sherryhsu/session-vs-token-based-authentication-11a6c5ac45e4&lt;/a&gt;  )&lt;br&gt;
 Here ,we are using Token based authentication. &lt;/p&gt;

&lt;h2&gt;
  
  
  Json web token(JWT)
&lt;/h2&gt;

&lt;p&gt;JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.&lt;/p&gt;

&lt;p&gt;JSON Web Tokens are useful for:&lt;br&gt;
        Authorization&lt;br&gt;
        Information Exchange&lt;/p&gt;

&lt;h2&gt;
  
  
  JSON Web Token structure
&lt;/h2&gt;

&lt;p&gt;JSON Web Tokens consist of three parts separated by dots (.), which are:&lt;br&gt;
                   •  Header&lt;br&gt;
                   •  Payload&lt;br&gt;
                   •  Signature&lt;/p&gt;

&lt;p&gt;Therefore, a JWT typically looks like the following.&lt;br&gt;
                   xxxxx.yyyyy.zzzzz&lt;/p&gt;

&lt;h2&gt;
  
  
  Header
&lt;/h2&gt;

&lt;p&gt;The header typically consists of two parts: the type of the token, which is JWT, and the signing algorithm being used, such as HMAC SHA256 or RSA.&lt;br&gt;
For example:&lt;/p&gt;

&lt;p&gt;{&lt;br&gt;
  "alg": "HS256",&lt;br&gt;
  "typ": "JWT"&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;Then, this JSON is Base64Url encoded to form the first part of the JWT.&lt;/p&gt;

&lt;h2&gt;
  
  
  Payload
&lt;/h2&gt;

&lt;p&gt;The second part of the token is the payload, which contains the claims. Claims are statements about an entity (typically, the user) and additional data&lt;br&gt;
Ex:&lt;br&gt;
{&lt;br&gt;
  "sub": "1234567890",&lt;br&gt;
  "name": "John Doe",&lt;br&gt;
  "iat": 1516239022&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;The payload is then Base64Url encoded to form the second part of the JSON Web Token.&lt;/p&gt;

&lt;p&gt;Do note that for signed tokens this information, though protected against tampering, is readable by anyone. Do not put secret information in the payload or header elements of a JWT unless it is encrypted&lt;/p&gt;

&lt;h2&gt;
  
  
  Signature
&lt;/h2&gt;

&lt;p&gt;To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.&lt;br&gt;
            {&lt;br&gt;
                 "sub": "1234567890",&lt;br&gt;
             "name": "John Doe",&lt;br&gt;
             "iat": 1516239022&lt;br&gt;
                         }&lt;/p&gt;

&lt;p&gt;In authentication, when the user successfully logs in using their credentials, a JSON Web Token will be returned. Since tokens are credentials, great care must be taken to prevent security issues. In general, you should not keep tokens longer than required.&lt;/p&gt;

&lt;h2&gt;
  
  
  jsonwebtoken module
&lt;/h2&gt;

&lt;p&gt;To create JWT token, we can use  a module “jsonwebtoken”.&lt;br&gt;
It has a method to encode token.&lt;br&gt;
            sign(payload ,secret ,callback);&lt;br&gt;
    We can add time duration to the token using “expiresIn” property.&lt;br&gt;
Eg: 60, "2 days", "10h", "7d". A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (days, hours, etc), otherwise milliseconds unit is used by default ("120" is equal to "120ms")&lt;br&gt;
Algorithm is HS256 by default.&lt;/p&gt;

&lt;p&gt;Let us consider the following Request handler which implements the above discussion.&lt;/p&gt;

&lt;p&gt;const exp = require("express");&lt;br&gt;
const userRouter = exp.Router();&lt;br&gt;
const jwt = require("jsonwebtoken");&lt;/p&gt;

&lt;p&gt;userRouter.post("/login", (req, res, next) =&amp;gt; {&lt;br&gt;
  //get usercollection object from "req.app.locals" object&lt;br&gt;
  let userCollectionObj = req.app.locals.userCollectionObj;&lt;/p&gt;

&lt;p&gt;//compare username&lt;br&gt;
  userCollectionObj.findOne({ username: req.body.username }, (err, userObj) =&amp;gt; {&lt;br&gt;
    if (err) {&lt;br&gt;
      next(err);&lt;br&gt;
    }&lt;br&gt;
    //if user obj is null,then send "invalid username" to client&lt;br&gt;
    if (userObj == null) {&lt;br&gt;
      res.send({ message: "invalid username" });&lt;br&gt;
    }&lt;br&gt;
    //if user obj is not null,compare passwords&lt;br&gt;
    else {&lt;br&gt;
      bcrypt.compare(req.body.password, userObj.password, (err, isMatched) =&amp;gt; {&lt;br&gt;
        if (err) {&lt;br&gt;
          next(err);&lt;br&gt;
        }&lt;br&gt;
        //if passwords are not matched&lt;br&gt;
        if (isMatched == false) {&lt;br&gt;
          res.send({ message: "invalid password" });&lt;br&gt;
        }&lt;br&gt;
        //if passwords are matched&lt;br&gt;
        else {&lt;br&gt;
          //create a JWT token and send it as response to client&lt;br&gt;
          jwt.sign(&lt;br&gt;
            { username: userObj.username },&lt;br&gt;
            "abcdef",&lt;br&gt;
            { expiresIn: 120 },&lt;br&gt;
            (err, signedToken) =&amp;gt; {&lt;br&gt;
              if (err) {&lt;br&gt;
                next(err);&lt;br&gt;
              }&lt;br&gt;
              res.send({&lt;br&gt;
                message: "user logged in successfully",&lt;br&gt;
                token: signedToken,&lt;br&gt;
              });&lt;br&gt;
            }&lt;br&gt;
          );&lt;br&gt;
        }&lt;br&gt;
      });&lt;br&gt;
    }&lt;br&gt;
  });&lt;br&gt;
});&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Handling Errors in Express Application</title>
      <dc:creator>Rajesh T</dc:creator>
      <pubDate>Thu, 23 Apr 2020 13:49:06 +0000</pubDate>
      <link>https://forem.com/rajesh04159786/handling-errors-in-express-application-162m</link>
      <guid>https://forem.com/rajesh04159786/handling-errors-in-express-application-162m</guid>
      <description>&lt;p&gt;Error Handling refers to how Express catches and processes errors that occur both synchronously and asynchronously. Express comes with a default error handler so you don’t need to write your own to get started.&lt;/p&gt;

&lt;p&gt;An error can be occurred in an Express application in the following two cases.&lt;br&gt;
      1.When requested route is not found in server&lt;br&gt;
      2.When the request handling middle ware generates an error.&lt;/p&gt;

&lt;h2&gt;
  
  
  Handling unavailable routes 
&lt;/h2&gt;

&lt;p&gt;Express Application creates a routing table in the order of route handlers in the application. When  a client makes a request,It can start comparing the request handlers in the order of they derived.&lt;br&gt;
If no match found,then it returns an HTML response with error message in it. We can handle this error by adding a middleware as last one in the application.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.use( (req, res, next) = &amp;gt; {
res.send(`path  ${ req.url } of type request ${ req.method }is not found`);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;});&lt;/p&gt;

&lt;p&gt;This middleware function can execute for every client’s request. So , by placing this  as last one,we can make it respond only for unavailable paths.&lt;/p&gt;

&lt;h2&gt;
  
  
  Handling error of  request handling middlewares
&lt;/h2&gt;

&lt;p&gt;Whenever an error is occurred ,the default Error handling middleware of express can deal with that.&lt;br&gt;
The default error handling middleware take four objects like below.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    (error, request , response , next )=&amp;gt;{}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;When an error is occurred in execution of request, the Express creates an Error objects and handover it to default error handling mechanish by suspending the execution  rest of code in that request handler. &lt;br&gt;
One can throw an Error  object to that default error handler by using&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;            let err=new Error(“error message”);
    next(err);  //this will call error handling middleware
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Note:  next() will call next middleware in the list where as next(err) will call error handling middleware&lt;/p&gt;

&lt;p&gt;Now add the following  error handling middleware  as last one in the list and just above list() method.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;        app.use( (err , req , res , next )= &amp;gt; { } ); 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;So the final order of route handlers in express app should like below&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    //write all request handlers
    //write middleware to deal with unavailable paths
        app.use( (req, res, next) = &amp;gt; {
res.send(`path  ${ req.url } of type request ${ req.method }is not found`);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;});&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    //write error handling middleware
    app.use( (err , req , res , next )= &amp;gt; {
console.log(err.stack);
res.send(“something went wrong!!!!”);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;} ); &lt;br&gt;
        //assign port number&lt;br&gt;
        app.listen(some port number here);&lt;/p&gt;

</description>
      <category>express</category>
      <category>node</category>
      <category>errors</category>
    </item>
  </channel>
</rss>
