Transcript for:
Node.js and Express Course Summary

hey what's going on guys welcome back to another  video so this is a full length six hours node.js   and express course for beginners and this  course is divided into 14 different chapters   we're going to cover the basics of node.js npm  async programming crud apis Express Express   middleware user authentication and mongodb  we are also going to build two projects as   we progress along the course you will find all  the details of the course content along with   the timestamp in the description of the video  so that you can jump to any topic directly so   if this sounds interesting then stick around  also don't forget to subscribe the channel   and press the Bell icon so that you don't miss  the videos like this one so let's get started foreign [Music] guys so before we go into the Hands-On with the  node.js we need to First go through some of the   slides and understand what actually node.js is why  this language is so popular which apps actually we   can build with node.js and what is the difference  between a node.js and the browser so we will start   with introduction to node.js so node.js is an  open source cross-platform JavaScript runtime   environment node.js runs on JavaScript V8 engine  this is the core of the Google Chrome and allows   us to run JavaScript outside the browser and also  makes nodejs much performant node.js app runs in   a single process without creating a new thread  for every request when node.js performs any input   output operation like reading from a network  accessing a database or a file system instead   of blocking the thread and wasting the CPU Cycles  node.js will use a callback function node.js uses   event driven non-blocking input output model  to handle concurrent request with a single   thread now let's see why node.js is so popular it  uses JavaScript as its main language to build web   application with just JavaScript we can build  front-end as well as backend applications which   means node.js is everywhere on the client and on  the server node.js is primary a JavaScript runtime   environment runs on V8 engine and V8 engine has  an ability to compile and execute JavaScript   at a lightning fast speed and that makes node.js  application very fast and performant node.js uses   basic event-driven architecture and it handles  multiple requests with a single asynchronous   thread this reduces the workload on the CPU as  well as the memory this makes our application   lightweight node.js has more than 700 000 modules  in their npm registry and using the ready-made   modules instead of coding which reduces the  development time and results of faster time   to the market Now microservices API designed  with node.js is getting extremely popular it   can handle many simultaneous requests and create  the apps without decreasing speed or performance   and node.js is enabled to build flexible apps that  can run smoothly on cross-platforms by creating   apis and whether it's a Linux machine or Windows  or Mac OS npm and its simple structure help to   build the ecosystem of node.js and npm has more  than 1 million open source packages which we can   use freely now the last thing is that node.js has  evolved a lot in the recent years and it has made   it available for many hosting services like we  can deploy the node.js application or we can host   them anywhere in Heroku netlify Cloud now let's  understand what applications we can build with   the help of node.js so with the help of nodejs we  can build a streaming web application like Netflix   Amazon we can build real-time web applications  like chat instant messaging we can build micro   Services which is popular modern architecture API  design and iot applications we can build any month   stack application like e-commerce we can also  build social media and networking applications   like LinkedIn medium and last creating restful  apis which can be consumed by any front-end or   mobile applications now let's understand what is  the difference between a node.js and a browser   so both the browser and the node.js they use this  JavaScript as their programming language building   apps that run in the browser is a very different  thing than building a node.js application and   despite the fact that JavaScript is all over the  place there are some key differences that makes   the experience radically different with browser  we can have access to the Dome elements web API   whereas with node.js we have modules to access  file systems and Os node.js supports both common   JS require an es module system where we use  the import to import any package while in the   browser we are now seeing that ES modules are  being implemented so before you jump into the   node.js there are some JavaScript Concepts  that you should know you should know about   classes arrays and objects functions scope Loops  variables expressions async and a weight closure   a sync program and callbacks event Loop and types  so few of the topics like event Loops types we are   going to cover again in the node.js course but  for all the other topics I already have video on   the JavaScript topics I'm going to add the links  in the description so that you can check it out   later on now let's go and install the node.js  so if you want to install the node.js you can   simply go to the documentation of the node.js and  then based on your operating system you can just   install the latest version or the recommended for  most users so let's go to the browser so I'm going   to minimize this and I will go to browser and  I will have node js and the first link is the   node.js I will just zoom in the screen and you  will see that now I am using a Mac machine so so   that's why I have a Mac OS and you can download it  either this one or this one you just need to click   on it you will have an installation file and then  let's do that so I'm going to click on it and now   you will see that my installation file is open now  if I click on it then it is going to open a wizard   so let me open a wizard and then you just need to  click continue continue or on Windows next next   next and then you just need to install it so now  once you install it now what we are going to do is   how we can verify that the node.js is installed on  the machine or not so what I will do is let's open   our Visual Studio code all right so now I have my  visual studio code and now what I'm going to do is   I will go to the terminal and in the terminal what  I will do is I'm going to zoom a little bit and   here I'm going to type node hyphen V and this is  going to give me the version of the node.js that   is installed on my machine so I'm going to click  enter and you can see that this is the version I   have installed and with the node.js you also get  a npm which is a node package manager which will   help you to install the dependencies and manage  dependencies so what I will do is I'm going to   have npm hyphen V and this is going to give me  the version of the npm that I have on my machine   all right so what we have to do is first let's  create a folder for our project so I will go to   CD documents so let me go to the documents folder  I will have a codes I'll write in here I'm going   to create make directory of node.js tutorial  then I will go to my trajectory so I will have   the node.js tutorial now I am in that directory  and now what I'm going to do is I'm going to open   the directory so let me open the directory so  I'm going to go to the documents I will go to   the codes I will go to node.js tutorial and I'm  going to click on the open so now I have it open   and now let's go to the terminal and what I will  do is I need to init my packet Json file so I will   have the npm in it and this is going to give me  the package.json file so it's asking me for the   package name so I will have the node JS tutorial  the version is 1.0.0 the description is this is   node js tutorial for beginners and then we have  the entry point which is the index.js I don't have   any test commands now get repository right now no  keywords no author I will give the author name as   the page malvia no license okay so I'm going to  have the es now you can see that I have a packet   Json file now inside this packet Json file what  I will do is I'm going to create a script which   will be a start script so let me have a start  script and in this start script what I will do   is whenever I do an npm start I need to have my  node.js and it should use index.js whenever I type   in PM start it's going to automatically fire the  node index.js so now we have it and now what we   have to do is let's create the index.js file first  so I'm going to go here I will have index.js all   right so this is my index.js file and the first  thing I will do is let's write simple console.log   and I'm going to write this as node js tutorial  for beginners and let's change this to capital n   and now this is a simple index.js file we have  a simple console log in it and now I want to   run this file so what I will do is let me clear  the console and here I'm going to type node so   whenever you want to run the node.js scripts with  the command line what we will do is we are going   to have the node and we are going to specify the  name of the file so for us it's the index.js and   when I hit enter you will see that whatever we  have in the console.log that is what is printed   here now the other way of running the node script  is we can also use directly the npm start so let   me have the npm start and I will hit enter and  this is also going to execute same node index.js   and we can see the output so this is the other  way of running it now let me change something   so what I will do is I'm going to add one more  console log so I will have the console.log and   I will say that this is the first tutorial on  node.js so now I made a change in the index.js   file so in order to see the output I again have  to run it so let's run npm start and now you will   see that we have it but what I want is whenever  I make a change it should automatically detect   and it should execute it so for that we have  a package called node mod so let's install the   node mod so what I will do I'm going to clear the  console and then I can install npm install hyphen   G node mod so either you can install it globally  so that it will have on all the projects or you   can just install it for a this project as a Dev  dependency so for now I will just install it as   a Dev dependency so I'm going to have this hyphen  hyphen save and hyphen there and then I will hit   enter so this is going to install the node mon  now let's go to the packet Json and you will see   that for the dev dependency we have the node mod  and now what I will make a change here is that   I'm going to run my application with the help of  a node mod so let's have a node mod here I will   save it all right now let's have npm start and you  will see that now the node mod has started and it   is now watching all the files with this kind of an  extension with the JS MJS or Json file so if we go   to the index.js and if I add a new console I will  make this we will cover node.js with command line   all right and I will save it and you will see that  when I save it my script is automatically executed   and then we have we will cover node.js in line so  this is how the node mon is a very useful package   while we work on the node.js application the next  thing what I want to show you is that how we can   exit from a node.js program so so now this is a  node.js program it is running and if you want to   exit from the node.js then you can use control  plus C so that is going to give me my terminal   back and this is one of the way where you can  use the control C but if you want to exit from   the node.js script programmatically then we will  see how we can do it so node.js has a process as   a core module provided so that process score it  allows us to programmatically exit from a node.js   program so now let's see how we can use it so we  have a process as a core module provided by the   node.js and we can simply use process dot exit so  this process has a lot of methods on it like EnV   to fetch the environment variables to exit but we  are going to come to that later on so I will use   the exit and I'm going to pass The Code by default  the exit code is 0 which means a successful exit   but we can also give the code as one so let's have  a zero and I will save it and now let's start so   I'm going to use the npm start so let me clear  the console first so I will clear the console all   right so now what we will do is now let's start  the application so we will have the npm start   and this is going to start our application but now  you will see that I want to do a programmatic exit   and that's where I will going to change the 0 to  1 which means that the application will crash so   if I save it then you will see that the app crash  waiting for the file changes before starting and   there is a different way of writing the same thing  we can actually use the process so let me have the   process dot exit and we can give it as one so they  both are same but it's a different way of writing   so I will save it and we will see that we still  have the so I'm going to change this to 0 now and   we will see that now we don't have the exit and  if I change it to one then we still see that we   don't see anything or we are not getting exited so  this should be code so I will save it and when we   have the X exit code then it exit our application  programmatically so the next thing we want to see   is how we can read the environment variables in  node.js so what I will do is let's remove or let's   comment this out and I'm going to create a new  file which will be e and V Dot JS this is simply   an JS file for environments which I have created  now in this file what I'm going to do is that   whenever I want to have some environment variables  so let's first exit this application and now what   I will do is I want to pass some environment  variables to my application so let's clear the   terminal and I want to pass environment variable  as name so I will give the value as the page then   I also want to pass the profession so let me have  my profession as developer all right and I want   to pass these two values or these two environment  variables to my application so my application I'm   going to start with env.js and I will hit enter  but you won't see anything but because we pass   the values we pass the environment values but we  don't know how to read those environment values   so here again we can make use of the process core  module so what I will do is I'm going to have the   console.log and in the console.log I will have  the process dot EnV and then I want to have my   name of the environment variable so the name was  name and the other one was the profession so let   me have the other one as well so I will have  the profession and now in this case I'm going   to run it again so I will pass it again and I  will enter and then you will see that we have   the page we are able to fetch the value from the  environment variables using the process.enb but   we have an undefined for the profession and that  is because uh the spelling is incorrect so this   will be profession I will save it and then I will  run it again all right so now I see that I have   the page and developer but this is one of the way  you can do it the other thing what you can do is   since you are not going to pass the environment  video tables from the command line we are going   to create a DOT EnV file so let me create a DOT  EnV file for the environment so I will have the   dot EnV so this is a one environment variable  files and I'm going to add all my environment   variables here so I will create the name and  I will name give the name as the page I will   also create the profession and I will give this as  developer and I will have a course so let me have   the course and this will be node.js now we have  this environment variable file and now we want   to fetch the values from this environment variable  file so for that what we can do is we can make use   of a package called dot EnV so let's install  that so what I will do is I'm going to have   the npm install dot EnV all right and I will hit  enter and this will help me to fetch the values   the configuration values from the EnV file so if  we go to the packet Json and if we go down and we   see then we have a dependency installed and now  if I want to use it how I can do that what I will   do is I'm going to go here I will use the require  and we have to require the dot EnV dot config so   we will fire a config function I will save it and  now let's go and start so what I will do is I'm   going to clear my console and I will have the node  and I will run the envjs file now this time you   will notice that I am not passing the environment  variables in the command line so I'm going to hit   enter and you will see that we fetch the values  along this I also want to fetch the course so I   will have this and what I'm going to do is uh I  am starting a new series on so I will have this   and then what I will do is I'm going to save  it and now let's give a try so now you will   see that what we have is I am going to start a new  series on developer which is wrong so this should   be oops so this should be B course so let me have  the codes I will save it and now we can see that   we have the page developer M I am starting a new  series on node.js so this is how with the help of   dot EnV you can do it there is another way that  if you don't want to use the required to import   the dot EnV what we can do is I will save it and  then now I will run the node.js then you will see   that I have all the values as undefined because  now node.js doesn't know from where to get the   values of the environment variables all right so  what we will do is I will go here and here what I   will do I'm going to write node hyphen r i want to  use the dot EnV slash config and I have to apply   this config to my env.js and I will hit enter  and now we see that we have a problem because   we have made a spelling mistake so let's do clear  and then I'm going to use the dot EnV enable it   enter and you see that we still get the values  the page developer I am starting a new series   next thing we are going to cover is the repl which  is a read evaluate print and loop so this is a   node command line so what I will do is I'm going  to create a new file so let me create a new file   oops not here I want to create a new file in my  project and I will name it as repl.js so whenever   we want to execute any node script what we do  usually is we do node and we give the file name   so let's have the index.js but now what I want  to do is I want to use the node command line so   let's go to the node command line so if you just  type node and if you hit enter then you will go   to the node command line so here you can see that  this is the node command line and here we can do   some evaluations and we can do some calculations  so let me start with a console.log and I will say   the page all right and then I'm going to hit enter  so you will see that I have the page printed so   what is this r e p l so let let me type r e p l  so this is read evaluate this will be print and   then look alright so this stands for repl so what  this means is that it's going to read the line of   code which you have in the node console and then  it's going to evaluate it and then it will print   the value and then it's going to repeat the same  thing for the next statement so this is what repl   and what we can do is I mean it helps us to Simply  do the calculations on the fly so we can also do 5   if this is triple equals to 5 then you will see  that I don't even hit enter but it gives me the   result so if I hit enter then it's going to give  me the same thing so that we can do now it also   helps us sometimes to write some functions so  it automatically knows that we have to write a   function so if I type something function and let's  have a function as Generate random number and then   what I will do is now when I hit enter Then it  automatically knows that it's a function and I   have to write something more so what I will do is  I'm going to have a return here and what I will   return I will just simply return math dot random  so let me have the math dot random all right and   then I will just finish this function okay so  now I have finished the function and now let's   try and use it so I'm going to run the function  and I will call this function and let's see so   we see that whenever we call a function we every  time get a random number so this is how you can   use this uh node console but it also gives one  more thing I mean whenever you type something   it automatically gives you an auto generated sub  so when I simply type generate then you will see   that if I hit tab then it's automatically give  me the autocomplete stuff and you if you want   to explore some JavaScript objects then we can  also check here so what I will do is that I can   type the number I will add Dot and then I will add  the tab so it will give me all the properties that   what I can use on the numbers so if you want to  see the global objects then and you can do that   as well so let me come out from it and now if I  want to use the global then I can use simply the   global this should be Global dot Tab and then you  will see that it has all the global objects like   error child process clear timeout constant and  many things now other thing on the repl which I   want to show you that this we used in the console  but if I want to use it programmatically then how   I can do that so what I will do is I will go here  I will just remove this and here what I will do   is I will have constant r e p l and there is a  module which is rep also I will use the require   and then I will have the repl and now what I will  do is I'm going to create another constant with   the local and I want to start my node console so I  will have the start command all right I will save   it now let's go and run this application so what I  will do is I will see Ctrl C that will help me to   exit so let me have the control c i will clear the  console and then I will type node repl.js and you   will see that when I click on it I automatically  go to the node console now one thing you can do is   that whenever you want to start your node console  you can use this ripl start but you can also pass   something here so the node console started all  right I will save it and then let's give a try so   first let's close this and now I will again run  it and here you will see that the node console   started and now you can try to do the same thing  so what I will try to do is if I want to write a   console DOT log the page then you will see that we  have the console.log the page but sorry there was   a syntax error so I will have this and I will hit  enter and if I want that I should look like a Unix   machine then I can have a dollar here all right I  will save it and let's give a try so I'm going to   have close I will start it again then in this case  you will see that we have eight dollars so we can   do this and what I will do is is that whenever  I exit this a node command 9 then in that case I   want to print some message so let's do I have a  local dot on and whenever I have an exit I want   to run a callback function all right and on that  I want to have a console.log and I will say that   uh exiting r e p l all right and then I can have  the process.exit so that will exit my command line   so I will have the process dot exit all right I  will save it and now let's give a try I want to   exit so I will click on Ctrl C then I will run  it so let me clear the console first so I will   clear the console and I will run my repl.js all  right I have this and here I want to exit it so   in order to exit I will again type Ctrl C and when  I type Ctrl C you will see that we print this exit   repl and then we are exiting from the node command  line all right the next thing I want to show you   is that whenever you run your node application  and if you want to pass some arguments how you   can do that so let's go to the arguments so what  I will do here is that I will just create a new   file so let me create a new file I will have the  arcumbent.js and then how I can pass the arguments   okay so we we run the application with the help  of node argument.js all right nothing is going   to print because we don't have anything here and  I want to pass the arguments so what I can do is   I can have the node argument and now I can pass  the arguments which I want so I want to pass Joe   or let me pass the page I will hit enter nothing  is going to happen we can also pass the argument   like this name is equals to the page nothing is  going to happen now what I want is that how we can   read this argument in our JS file so we can use  the same thing we can again use the process which   is very powerful module we have in the node.js so  here I will use the process dot argument so if you   see we have the arc so let's use this R so in this  process dot argument what we have is the first   line we actually have the path of our node where  we have installed the node.js the second argument   is actually the file name which we want to execute  and the third one is the argument that we want   so if we go and if we do a console.log so let me  have a console.log of process dot Arc then let's   see what we can see here so what I will do is I'm  going to go here I will hit enter and we see that   okay I have misspelled the console all right let  me clear it and let me run it again then we see   that it's a array and the first index contains the  value as the path of my node the second contains   the path of my the file which I want to execute  and the third one is the argument so what we can   do is we can actually use the slice so let me have  the slice and I will slice it as two and then I   will have it zero and I will save it and now let's  do it and now we can see that we have the page   which is name is equal to the page what I will do  is I want to print all the three stuffs so what I   will do I will have the process dot argument and  on that I can use the for each so let me have the   for each and for each of the argument I'm going  to have the value and the index of it I will have   the arrow function and then I will have simply a  console log and let's have the backticks I will   first print the index so let's have the dollar  Index and the second I want to print the value   whatever the value is available so y will have the  value all right I will save it okay I will just   comment this out we don't want that and now let's  run it so I will run it and you will see that at 0   index we have the path of the node first index we  have the path of the file which we want to execute   and on the second index we have this all right but  what we want is uh I mean we don't want this name   equal to the page we only want that if we have  an argument dot name then we should be able to   get the value as the page so there is a package  which we can use and that is called the minimist   so let's install that so I'm going to install the  minimist all right I will hit enter the package   is installed we can verify in the packet Json and  with the minimist what we can do is let's go to   our argument file and what I can do here is that  comment this as well and what I will do is I'm   going to have a constant argument new and I will  use the same I will do the slice and I need the   index of 0. so this is going to give me uh if we  go and console it first so it's going to give me   name equal to the page so let me have a console  I will have Arc new all right I will save it and   then I will just run the node mods so nodemon  on the arguments all right and we see that the   command not found all right so that is because we  have to copy this and let's go to the packet Json   and I will change this all right and now if I do  NTM start then okay we see that we have the node   one and we see that the value is undefined  and that is because we did not pass any of   the arguments so what I will do is I will just  close this we don't actually needed the node   my on what we will do is I will simply go to the  node or let's go and this okay I have this node   argument.js and then name is equal to the page  and if I hit enter then you will see that this   argument is the so I need something that if I use  the argument new DOT name I should get the page   as the output and for that we can use the minimis  so what I will do is we already have the minimist   and I will pass this information in the minimist  all right and I will do this okay I will save it   and now let's go and check so if I do this then we  see that minimis is not defined so let's add it so   I'm going to use constant minimist is equals  to require minimist and now we can give a try   so let me clear it so I will clear it and then  let's use it so now you see that we still have   be undefined so that means we are doing something  wrong okay so we don't need to pass this now so I   will just remove it and now if I save it then we  will be able to get the page all right so there is   a catch that whenever you use a minimist what we  have to do is we have to give our key with hyphen   hyphen so that where it will be able to know that  this is the key so I'm going to hit enter now you   will see that we have the page here so with the  help of minimist we can actually uh retrieve or   read the values or the argument values which we  pass in the command line the next thing we are   going to see is how we can do the output to the  command line using node.js so let's go and let's   create a new file for the output so I will do here  output dot JS I will just correct the spelling so   we have the output dot JS and in this let's have  simple start with a very simple so I'm going to   have X as one all right and I will have a y as two  all right and the easiest thing we know that how   we can put the values in the console is simply use  the console logs so let's have a console log and   I want to print X and Y all right I will save it  and when I run the output.js it's going to give   me one and two now we can also use the format  specifier and the format phrases so if we want   to form it a variable as a string then we can  use the percent s and this will actually format   variable to string and similarly if we want to do  it for a number we can use percent D if we want to   do it for a integer part then we can use percent  I and if we want to do it for an object then we   can use the percent o let's take an example of  it so let me have a console DOT log and here I'm   going to write I am so I'm going to give a name  here I am the page which is a string and my age   is percent let's have D all right and now I want  to pass T values so the first value is my name   the page and the second is my age so let me pass  the age as 25 I will save it and now let's give a   try so if I go and use it then you will see that  I am in the page and my age is 25. so this way   you can actually use the format specifier and you  can format the variables the next is if you want   to clear your console you can also use the console  dot clear and this way you can clear your console   so if I go and run it then you will see that my  console will be clear because first it will do   console log then it will do this console log and  then the console.clear another interesting thing   is you also have a console.count so if your string  or if you print anything multiple times is going   to keep a count so let's take an example so I  have a console.count and I will write it here   I am the page all right and now what I will do  is I'm going to copy this twice so let me copy   I will copy again and this time I'm going to  console something else so console.count and I   will write I am nikesh all right I will save it  and I will gonna run it so let's run it so it's   going to clear the console first and then we will  have this information so it's going to print the   count as well so I will hit enter and now you see  that I am the page the count is one I am the paste   the count is 2 because it's printed second time  and then I have I am nikesh with the count one I   can also reset my account so if I want to reset my  account what I will do is I will have console.log   dot reset count reset and I will reset my account  for I am the page so I have I am oops the page   and once I do it then I will add the console log  okay here and now in this case you will see that   we will have the IM the page one I am the page  two then I am nikesh one then it will reset my   counter and then it will again have one instead of  three so let's go and check and you will see that   I have these two one two one and then I have reset  the counter and then I have again one so this way   you can reset the count now there are some cases  where whenever you're working on a project and you   want to print the stack of your code so what we  can do is let's comment this out so let's create   a function I will create a function all right and  this will be an arrow function and what this will   return is uh I will have a console dot Trace so  it's going to return the trace so I want to give a   function name so let's have this function name one  and then I will create an another function which   is a function two all right and this function is  going to call my function one so let me have the   function one and then let's call the function  two so I will call the function two all right   I will save it and now let's give a try so if  I run node.js then you will see that the trace   is printed so it is printing the function  two function 2 is being called then it will   call the function one so you have this function 2  here and you have the function one so in this way   you can print the stack trace and it will help  you in the debugging as well the next thing you   can put console is you can calculate the time  spent by your function so what I'm going to do   is let's create two functions so I'm going  to comment this out and then what I will do   is I'm going to create two functions so let me  have a function sum and this is going to print   the sum so for this I will have the console.log  and I will have the back stick I will have the   the sum of 2 and 3 is I will have the dollar  and I will have 2 plus 3 here oops this will   have a backtick here so I'm going to cut it and  I'm going to add my backtick here and a similar   I will have another function which will be a  multiply so let me have the multiply and this   is going to give me the multiplication of 2 and  3 so I'm going to change this to aspect so now I   have two functions and I want to see how much time  is actually spent to execute those two functions   so let me create and let's have a constant I will  have a measure time function and this measure time   function will actually going to calculate the time  spent for each of the functions so how I can do is   I want to First calculate the time for this sum  execution so I will have a console dot time and   for sum and now I want to call my function sum so  let me call the function sum and then once it is   executed I want to stop my time so Time end all  right and this time end for sum now we can do the   similar thing for the multiply as well so let me  add it here I'm going to change this to oops I'm   going to change this to multiply all right and  now let's call this function measure time so I'm   going to call the measure time all right I will  save it and now let's execute it so I'm going to   use node output.js and now you will see that the  sum of 2 and 3 is 5 which is correct and this is   the time taken to execute the function similarly  for the multiplication it's 6 and this is the time   taken for the multiplication all right so this  way you can also uh in the console log you can   add execution time of a function as well now one  interesting thing I want to show you is that you   must have seen in a lot of uh whenever you install  the package you see there is a download download   tick bar so how how they can create it so let's  create that progress bar so for that we have to   install a package which is a progress bar so let's  install it so what I will do is I will go here and   I will have the npm install progress all right so  this will be progress I will hit enter okay and   we have the progress if we go to the packet Json  we have the progress now how we can use this so   what I will do is I will first comment this out  we don't want this anymore all right I will save   it and now what we can do is we can actually write  the code for the progress bar so what I will do is   first we need to use the progress bar so I will  have the progress bar and this will be required   and let's add the progress all right we have  the progress and now we can make use of we need   a constant so let me have a bar this will have  a new progress bar and in this what I want is I   want that whenever we are downloading something  I want to use the bar so this will be bar and I   also want to use the uh the speed or the rating  which it will get downloaded so it will be BPS and   I will have the percent and I will also use the  expected time and then what we will do is it also   has an another argument which is the time how much  you need the total progress bar so I will have a   total of 20 bars maybe so let's have a 20 here all  right we have it and now I'm going to create a set   interval function so let me have a constant timer  is equals to set interval all right and in the set   interval we are going to have a function and we  want it or every 100 milliseconds all right and I   will use the bar dot tick so it has some functions  inbuilt so I will will have the bar dot take and   whenever my bar is completed so I will have the  complete then in that case I want to just clear   the intervals so let me clear the interval and  I will have the timer all right I will save it   now let's try it so what I will do is I'm going to  clear the console I will use the output and I will   hit enter and we see that we have an error so the  error is the new progress bar let's go and let's   check so yeah so the problem is this is capital  so let's change this I will save it and now let's   clear and run it again and now you see that we  have this progress bar so this is how you can   actually use the outputs on your console so it's a  very powerful and whenever we install any package   also you see that we have something like similar  to it on whenever we install any packages so this   can be done with the help of the progress bar  now one thing we you can also do is if you want   to change the color then what we can do is we can  install a package called chalk so I will install   a package npm install c-h-a-l-k and I will hit  enter and this is going to give us some beautiful   colors if we want to add it in our console log so  how I can use that so let me go and use it so I'm   going to go here and I will have a console.log and  inside the console.log I can use whatever color I   want so I will use the chalk dot green and this is  oops this is node js tutorial and now I will run   it and we see that we have a color or not so let  me run it and we see that we get an error because   we did not use the chalk require so let's go and  import it so I will go here I will have a constant   shock that will be equals to the required and I  will add the shop all right let's give a try so   if I clear the console and I run the file we still  have chalk has already been declared so where it   is declared we have to find it out so it already  imported by default so I will just remove that all   right I will save it and now let's give a try all  right so if I run it then we see that we have an   error because uh chalk 5 so if we go to the packet  Json then we see that the chalk 5 is actually uses   es module so what we will do is we can install  the chalk Force so I will go and change this so   let's go and install the chalk4 I will hit enter  and this is going to change the version to 4. now   let's give a try so in the chalk 4 we can use it  with the help of common JS modules so I'm gonna   run the output and you will see that we have this  in the green color now so we can also make this in   the blue so let me change this to Blue and it's  very simple so now run it and you will see that   we have a different color in our console output so  this is how we can use the output to the command   line using node.js now let's take an example for  the input as well how we can accept the input   from the user in our command line all right so I'm  going to create a new file I will have the input   dot JS all right and in the input JS what we  can do is we can actually make use of a read   line so this read line package is going to help  us to read a line in the console from the user so   what I will do is I'm going to have a constant  read line all right and that is equals to the   require and I will have the read line now with  the read line we need to create an interface for   the input and output so what I will do is let's  have a constant I will have a read line all right   and then we have a create interface and with this  create interface it's going to have the input and   it will have the output so for the input we can  use the process dot standard input so this is the   standard input for output we can use the standard  output so let me have the process dot standard   output we have the interface and now what we can  do is we can have this RL dot question so here we   can have the question whatever question we want  to use so what I will do is I'm going to have a   backtick and I will have what is your name I will  have the question mark and when you have this RL   dot question uh you will ask a question what is  your name and then you will wait for the user to   add the input once the user adds the input and it  hits enter Then a callback function will be called   so let's have this callback function so sorry  I will have the name and this is the Callback   function and then we can have the console log here  so I will have the console log and we are going to   have a greeting so here I will have the hi I will  have the name oops this will be dollar all right I   will save it and then what we will do is once we  have the user input I want to close this so let   me have the read line Dot close all right I will  save it and now let's give a try so what I will   do is I will clear it and then I'm going to use  the node input dot JS so let me have the input.js   and I will enter and you will see that it's now  asking for a name and it's the execution is now   halted so what I will do is I will whenever I have  my name and I enter a callback function which is   this callback function will be called and my name  will be printed with hide the page and then this   read line will be closed so let's have it I will  have the the page and I will hit enter and you   see that we have hi the page so this way we can  use the input from we can take the input from the   user from the command line uh there is one more  package called prompt sync where if you want to   get rid of this callback function you can use the  prompt sync let's take a look on it so I'm going   to have the npm install prompt sync prompt sync  all right and it's going to get installed oops   I have a problem okay so I actually misspelled  it so it will be prompt sync and this is going   to get installed if we go here we can verify it  now how we can use the prompt sync what I will do   is I'm going to have a constant I will have the  prompt this will be require and here I can use   the prompt sync and since prompt syncs actually  gives a it's it's a function so we need to execute   this function to use it so I will have an empty  uh brackets to execute the function and now how   can I use it so for now I will just comment this  out we don't want it we can now have let's have a   simple constant name then the name will be I want  to prompt what is your name and then simply have   a console log so I will have the console DOT log  and then I will have the name here all right or   we can simply use this again so here we don't need  to add any callback function all right now let's   give a try so if I run the node input JS then  it will ask for the name I will type the name   then you will see that it has hide the page but  here there's a problem that now you need to exit   from the command line then you have to use the  control C so we have covered a lot of basic about   the node.js I know that this is nothing related  to any project or any real world examples but   it's important to go through first the basics and  then go for the building real world applications all right guys so in the previous video we saw  that we have installed the node.js on our machine   and we know that when we install the node.js  we also get npm so here also if you see then   we have the node.js version and when you download  the node.js and install on your machine you also   get the npm so let's go and check in our code base  uh the version of the npm and the version of the   node.js that we installed in our previous video  so I will go back here and I will go and I will   type node hyphen V and this is going to give me  the version of the node.js which is installed on   the machine now for the npm we can do npm hyphen V  and we have the npm version as 8.1.0 so now let's   go through some slides about the npm understand  what it is and how this npm is so important while   building the node applications and why we need  to learn about the npm package manager alright   so now let's start with that npm it stands for  the node package manager and it's a standard   package manager for node.js application npm  as of September 2022 it has around 2.1 million   packages listed in the npm registry which makes  it a largest open source repository and we can   find any package on this npm registry npm it's a  way to download and manage dependencies for both   front-end and back-end applications using  JavaScript so you must have seen that when   we build the react application we use the npm to  download the dependencies like axios react router   Dome so it's a kind of a tool which can be used  for front-end as well as back-end applications   and there are two more alternatives to this npm  which is a yarn package manager and pnpm which   are the alternatives to the npmcli this is how  the npm website looks like and let's go on the   npm official documentation and let's explore  some packages all right so now we are on the   official documentation of the npm and we can start  searching the packages from here so while building   node.js application if I want to use a node then  I can type node Mon and I will be able to get the   node one package so here you will see the node one  if we want the axios for calling apis then we can   use the axios so it has millions of packages  which we can make use of in our application   now if I go to the documentation then we will  see that we have the npm CLI and this npm CLI   have some commands and most of the commands we  we are familiar with it when we actually build   the applications like npm in it so I have a list  of commands which we frequently use in which we   are going to use in the future while building  the react application so let's go through the   slide and the commands which we are going to use  frequently so the first command is the npm init   so whenever we want to bootstrap the packet Json  file we use npm init and then based on the options   we provide the values so we have already done this  in the previous video so if you have missed that   video please go and check it out the next one is  the npm install so when we have the packet Json   file which contains all the dependencies then  we just use the npm install to install all the   dependencies in the project if we want to install  a single package then we just use the npm install   and we give the package name now this comes with  a different flavors so if we use hyphen G then it   will install the package globally and if we use  hyphen hyphen save hyphen dev then it is going   to install the package under the dev dependencies  so we are also going to see some practical stuff   how we are going to use those flags next is the  npm installed package name and we give and add   the Red symbol and provide the version so that is  going to install a specific version of a package   in our application next is the npm update so  whenever we use the npm update it is going to   update all the dependencies that are listed in the  packet Json file and it will update to whatever   the constraints we have provided so we are also  going to see what are the semantic versioning   constraints at a later Point next is the npm  update package name and this is going to update   just a single package which we want next is the  npm Run task name so we usually do npm start which   actually behind the scene run our application and  it will help us to run all those scripts that are   available in the packet Json then we have the npm  list and this npm list is going to list down all   the dependencies that we have installed for our  project next is the npm view package name version   so suppose if you want to view a version of a  specific package in that case you can actually   use the npm view package underscore name you can  provide the package name and then you will provide   the version so it is going to give us the version  then you have the npm uninstalled which is going   to uninstall the package from our application and  last is the npm help which is going to list down   all the npm commands that we can take a look and  use it you will also find all this on the official   documentation so there are a lot of commands but  I have list down some of the important commands   which we are going going to use so now let's jump  into the visual studio code and let's give a try   on this npm commands all right so now I am on my  code base so this is the same code base which we   used in our previous video so let's start with  an npm in it so I'm going to write npm and I   will have init and when I try to do this you will  see that it gives us some information it will ask   us the package name which we want to give and I  have given the package name as node.js tutorial   so I'm not going to give anything here then  it is going to ask us the version which is the   1.0.0 then it's going to ask us a git repository  if we have a git repository then we can provide   the git repository here similarly it's going to  add some more information and when we provide   all the informations and then enter it's going  to create a packet.json file which is going to   look something similar to this so I'm not going to  do it because we already have it I just wanted to   show you how you can do it so now you see that  npm init is canceled I will clear the console   now in most of the cases you must have used  the npm install command so what it actually   do is when I write the npm install it will first  take a look on the packet Json file and in the   packet Json file it has all the dependencies  so when you hit enter it is going to install   all the dependencies with the latest version  that is available on the npm registry and it   will create your note modules folder and add all  the dependencies to this node module so you will   see that this is the node module and it will allow  all the dependencies here so this command is very   useful whenever you want to push your code to the  GitHub repository so usually you have a get ignore   file and in the git ignore file we ignore the node  module package because it's heavy in size and we   don't want to upload all the dependencies on the  GitHub repository and whenever you want to set   up a local project you will clone the repository  and then you will run the npm install so that is   going to create a node module folder and install  all the dependencies in the node module so that's   where the npm install is very useful the next  npm command is the npm install package name so   let's install the node mod so you will see that  I already have a node Bond here but I can try to   install it again so it is not going to create any  problems so I will have the npm install and I will   have the node mod I can give a flag of hyphen  hyphen save hyphen there and this is going to   install the node mon into my Dev dependencies  so if we already have a node mod let me change   and add axios so let's use the axios as hyphen  hyphen save hyphen Dev and if I hit enter then   you will see that we have the axios package which  is installed in the dev dependency so now there is   an another flag which is the hyphen hyphen save  optional so in that case what it will happen is   let's install colors so it's a package that will  allow us to have colors in our node.js console so   for that I need a hyphen hyphen save as optional  so I can make use of an optional flag here so   I will have the optional all right and now if I  hit enter then you will see that now we are going   to have a new object which will be an optional  dependencies and that is going to contain all the   optional dependencies similarly you can have no  option and no save all right so the next I want to   show you is that how to use the npm update so now  you will see that we have the different packages   installed with different kind of inversion and we  are going to see later what are these version what   is the meaning of this symbol and how to upgrade  it so if I want to update all my dependencies to   the latest version available in the npm registry  based on this constraint then I can use the npm   update so what I will do is I will simply use the  npm update and then I will hit enter and let's see   what versions get changed so I see that all the  packages version I have are already updated and   if you want to update any specific package then we  can simply use the npm update and let's update the   chalk so I will do npm update job and I will hit  enter and this is going to update my job package   now if you want to install a package to a specific  version then I can use npm install I will have the   installed chalk at the rate and I can give the  version so let's suppose you're working on a   react project and you want a specific version of  a react like the react 17 or react 16 then you   can use at the rate and you can add the version  which you want to use so this is just an example   then another thing which I want to show you is  the task coroner so what is the task Runner is   whenever you have this script object and in this  script object you define your test you define your   start so if you see here if I write npm start  then in the background it's going to fire the   node argument.js and that actually helps us the  task Runner so you can run different tasks with   the help of npm and you can Define more tasks here  like if you want to have a watch script or if you   have want to have a script that should run on dev  environment or on the production environment now   the other thing which I want to show you that  where does this npm install all the packages so   npm installed the packages at two different levels  and it depends on how we install the packages so   let me show you if I cancel this and if I type npm  install hyphen G and then I type any package name   so I will have the package name then in that case  with this hyphen G it's going to install globally   but if we are not using this hyphen G and we just  use the npm install I'm going to install the low   Dash so it's a utility Library so if we have  installed the low Dash then you will see that I   have the low Dash here and it's going to install  it locally to the project so this is the node   module and when we install it without the hyphen  g flat then it's going to install locally to the   project so if we go and scroll then we see that  we have the low Dash here and if we want to see   that what all packages we have installed globally  then we can do that I will clear the console and   we can drive npm root hyphen G and this is going  to give me the path where you installed your   packages globally so it's the user local library  node modules so the next I want to show you with   the node package manager that we have installed  the low Dash now I want to show you that how we   can use this package so what I will do is let's  close this and let's go to the index.js all right   I will just comment this out we don't want it and  then what I'm going to do here is that if we want   to use the package which we have installed locally  I'm going to have the constant underscore and this   will be equals to the required so you need to use  require as we are using the common JS so here we   can use the low Dash all right now we have the low  Dash and with this low Dash uh I mean if you don't   know about the load Edge you can go and check the  utility Library so it gives us a lot of functions   which will help us to perform uh operations on  the arrays and make it easy so what I'm going   to do is I'm have a simple array and I'm going to  have the values as 1 4 6 8 and then what I want is   I'm going to have a console log so let me have the  console.log and I want to divide my complete array   into small arrays with a small small chunk so what  I will do is I'm going to have underscore and I   will have the dot chunk and then in the chunk I'm  going to pass the array all right I will save it   and now let's go and run it so I will have the  node index.js and I will hit enter and you will   see that we have now arrays with a chunk all right  if I want a last value then we can have the last   and it's going to provide us the last value of  the array so this is 8. now let's understand a   case that if you are installing a package and  it has an executables so for that what we will   do is uh let's install the npm install cow say so  this is a new package which I am installing and   it's npm install cow say I will hit enter and this  is going to give us some executables in our node   modules so in the node modules it will have a bin  and all the bin will contain the executables so   if you remember that when you create the react  application you use something like this create   react app and you give the name of your app so  this npx is actually a node package Runner and   it will run the executables so what I will do is  uh we have the cow say so here what I can give is   I can give npx a cow say and I will I am learning  node.js and when I hit enter what this actually   uh package is doing is it will create a cow and  it in the cow it will say whatever we are typing   so I would enter then you will see that we have a  cow and I am learning node.js so this is one way   if you want to run your executables which are in  the bin folder now you can also do the other way   which is that we are going to have a constant I  will have the cows say and then I will have the   require and in the require I will have the cow  say all right and then I can make a console log   so let me have a console log and in the console  log what I have will have I will have the cow   and what the cow say is I will have the cow say  and then I need to provide some values I need the   text and text is I am learning npm module and then  we need to provide the eyes and the tongue so for   the eyes I'm going to have 0 0 all right and for  the tongue I'm going to have you so let me have   the U and then now let's run it so if I run this  okay let me go here and let me have the npm node   index.js I have to save the file so I will save it  and let's clear the console first and then run it   so you will see that we have the I'm learning  npm models so this is the other way of using   the package the next thing I want to show you is  about the package Json file so with the npm the   node package manager you always have to deal with  the packet Json file and the package.json file is   basically the Manifest file which contains all  all the information related to your project like   what is the name of your project the version  of the project all the dependencies whether   it's a Dev dependency or optional dependency  all production dependencies about the author   license so all the information related to your  project will be in the packet Json file so it's   basically a manifest file along with the packet  Json you also have the packet Json lock file so   this package.json lock file is actually a very  similar version of a packet Json file but it   contains the dependency versions so if I go here  sorry if I go to the packet Json file all right   I will close this and I will also open the package  lock all right in the packet Json file if you will   see then we have dependency with a versions so  I have a dependency of dot EnV and the version   I'm using is 1602 and I have a symbol of this  carrot so this is the version we are using now   in the package.json it is actually going to have  the exact version so if I go here and if we see   then we have a DOT EnV and I will make a search  of this dot EnV and here it will show that I am   using the latest version which is the 16.0.2 so  package block Json file will maintain all the   dependency and their versions the next is that if  I want to see all the packages that are installed   on my project so I have this project and I want to  see all the packages so I can use the npm list and   this is going to give me all the packages that are  installed on my project so if I want to see uh all   the packages which are installed globally then I  can pass the hyphen G flag and you will see that   on global level I have only two packages installed  which is a core pack and the npm itself now if I   want to see a specific version of any package  then I can use npm view Cow Say and I want to   have the version of the cow safe then we will see  that we have the version as 1.5.0 so this is how   we can get the version of any specific package  in the project if we want to install any older   version of the pack package then we can make  use of a npm install then we can have a package   name and then we can provide the old version  so this way we can install any Olden version   of the package and one more thing is uh if you  want to see that what all our versions that are   available for a package in the npm registry so I  want to see that what react versions are available   so for that what I will do is I can use npm view  react and I will have versions so this is going   to give me all the versions for the react that are  available so you will see that these all versions   of the react that are available all right now  let's understand about this semantic versioning   so let me show you some slides to understand the  semantic versioning better all right so with the   semantic versioning what we do is whenever we  installed a package so let's say we are using   the express and I want to install the express so  I will use npm install Express when I install it   I will see an entry in my package Json file as a  dependent agencies and inside the dependencies I   will have the express and with Express I will also  have a carrot symbol and I will have a version of   it now let's understand what this version means so  with the semantic versioning you have an Express   installed with 4.18.1 so the first digit which is  4 it is defined as a major version of the express   the second digit which is the 18 is defined as a  minor version of the Express and the last digit   one which defines that it's a patch version so  if we have a credit symbol on top of that then   it means that the minor version or the patch  version can be changed so that means if I do   an npm update it will either update it to a minor  version the newer minor version or a patch version   but it will never update it to the major version  which will become the 5.0.0 and sometimes you will   also notice that we have the still symbol then  it means that when you fire the npm update it   will only update the patch version is available  so so these you will see frequently there are   a couple of things like greater than or less  than or a range so in that case when you update   your dependencies it will update based on the  constraint that is added all right now let's see   if we want to uninstall any dependencies we can  make use of an npm uninstalled so what I will do   is I'm going to clear the console and then I will  uninstall the axios so I will do npm uninstall and   I want to uninstall axios so this is going to  remove the axios from my package.json file so   we don't have the axios here all right so the next  thing I want to show you that now we know that if   we install any package like low Dash or cow say  and if we want to use it we can use it with the   help of this require now let's see what if we want  to export a functionality from a node.js file so   what I will do is I'm going to create a file so  let's go here and I'm going to name the file as   car dot JS and in the car.js what I will do first  is let's create a constant I will have the Ford   all right and here I'm going to give a brand and  let's have the brand as far and I'm also going   to give a model so let's have a model as Fiesta  all right now I have created this Ford object and   now what I want is I want to export this so the  one way of exporting this is to use the module   dot exports and then I'm going to give the car and  now I want to use it in my some file so let's see   I want to use it in my index.js so I will go to  the index.js I will comment this out we don't want   this now and here what I will do is I'm going to  have a constant I will create car and this will be   coming from require and let's have the car I will  do a console DOT log of car and now let's see what   we see so I'm going to have the node index.js and  you see that we get an error which is the export   modules equals to car and car is not defined all  right so we see that the car is not defined so   let's go in our car.js and we defined car but we  don't know what car is so let me change this to   Ford all right I will save it and now let's go  back in our index.js I have the car and I will   try to run it all right and now you will see that  we have the object which is a branch as Ford and   model as Fiesta so I'm going to clear this out all  right and now here you can give any variable which   you want so if I give a variable of Ford then I  can print the fod all right and I will save it now   if I run it then I'm going to get the object now  this is one of the way now the other way is to add   the exported object as a property of the export  so I will go here and I will just comment this   out all right let me comment this out and what  I will do is I will have the export Dot and I'm   going to provide a property here so let's have a  property as data and to this data I want to export   Ford this will become exports I will save it and  now in this case what we will do is we will have   a very similar car and Ford but here in this  case the fault will be a object so if I run   it then you will see that we have an object data  and that will contain the object of the font so   this is the data and this contains the object  of the fault so what I will do is I'm going to   destructure this and now if I'm going to run  it then I will see that undefined and that is   because the property name which we added is the  data so we have to destructure the data actually   all right I will destructure the data I will add  the data here and now let's give a try and now   you see that we have the branch and the fault now  if we have more than one uh objects so let's have   an another object I will have the constant  Tesla and this will be let's copy this so   I'm going to copy this I'm going to add it here  the branch will be Tesla and the model will be   model 3 and now we can actually export the Ford  we can also export the Tesla so let me have the   Tesla as well I will save it and now let's go  to the index.js I have the data and here I will   have the let's console this data first so I will  clear the and let's have the node.js so now I have   a complete object which contains Ford and Tesla  so what we can do here is that uh I can go back   here and instead of this what I can do I can have  exports dot Tesla and I could also make this as   exports.ford all right and then now I don't need  this now we can make use here so here I can have   the Tesla and I can also have the Ford all right  and now let's copy this I will add it here and I   will also add it here so I will have the copy and  I will add it here and I'm going to run this then   you will see that we have both the objects there  are a couple of ways I uh you can use this you   can export the modules you can use the exported  object as a export property which is the export   dot you can give the property name now the next  thing I want to show you is that how you do a   console log of the objects so if you want to do  a console log of the objects how we can do that   uh I will go here and what I will do is I will add  the Json Dot stringify and in the json.stringify   what I will do is I'm going to first add the  object that I want to console log then the second   value I will give it as null or you can give the  undefined so you will see that when you hover it   on the stringify you will see what values you can  give you can give null and the third value will   provide the space which you want so I'm going to  add the space as 2. I will also add it for here   so this is going to beautify the object so I will  have the font I will give undefined this time and   then I will have two I will save it now let's  give a try so I'm going to run it and you will   see that we have the beautify objects so this way  the json.stringify can actually help to console   log the objects and add the beautification on that  all right so we can also change this to three let   me change this and let's run it again then you  will see that we have a little bit different   indentation so it provides the space to the  objects so that's all I have in this video so   in this video we covered the very important npm  which is the node package manager a tool how we   can use it in building the react application  and manage all the dependencies the second   thing is that how we expose functionality in the  node.js files either by using the module export   or adding the object to the exports property and  the last one was how to console log the Optics all right guys so we will start with how to  handle the errors in node.js and usually errors in   node.js are handled through exceptions so we throw  in exceptions with the keyword throw so there are   four different ways you can handle the error and  let's see each of them one by one so I will start   with first creating a file so I will create a file  and I will name it as error.js and the first way   to create is using the error object so let's see  how we can uh have the exceptions using the error   object so what I will do is I will simply have  an error all right and this error you can create   with a error object so I will have the new error  and inside this I can write whatever I want so I   will write something went wrong I will save it and  now let's run this so I will do node error.js and   I will hit enter all right and when I hit enter we  don't see anything and that is because we created   an error object but we did not throw that error  object or otherwise what we can do is we can also   check with the help of console DOT log and in  the console.log I can use this error dot stack   all right and I can also use the error Dot message  so first let's try and check the error dot stack   so when I throw it you will see that we have the  error stack we have the error object and we have   something went wrong and this is the complete  stack of our code we can also use if you only   want to see the message we can use the error Dot  message and this is only going to show the error   message which is something went wrong so if I run  it then you will see that we have this something   went wrong for that let's comment this out and  let's run it again so I will clear the console   and then I will run you will see that we have  something went wrong we can also use with the   help of throw so if we want to have an exception  then we need to throw that exception and to use   that we use a throw keyword so what I will do is  I'm going to comment this out and instead of this   I can use throw so let's have a new one so what I  will do I will have through and then I will throw   the new error object and inside that I will write  something I am error object all right I will save   it and now if we run it then we see that we have  a error which is IM error object and the stack and   we found that this error occurred at line number  five so this is one way you can throw the error or   you can handle the error using the exception and  use the error object but what if you want a custom   error object so for that what we can do is we can  actually extend the error object and what I will   do is I'm going to create a custom error.js and  in the custom error.js what I will do is I will   have a class I will write custom error and this  class will extend the error class so we have it   and now we can simply have a Constructor I will  type the message so whatever message we are going   to pass it we are going to get that message I  will have the super and I will add the message   now we can export it so we have already seen  in the previous video how we can use the module   export so what I will do is I'm going to use the  module dot exports and this I want to export the   custom error now instead of the error object what  we can do is we can import the custom error so I   will write the constant custom error and this will  be equals to require and then I will have the dot   slash custom error now we have this custom error  reference and now we can make use of it so what   I will do is I will simply have throw custom  error so we have to create a new instance so   I will have the new keyword and then we can have  that this is a custom error object I will save it   and let's comment this out otherwise we're going  to see two different errors so now I will run   it and here you will see that we have the custom  error now this custom error can be a bad request   validation or authorization failure or forbidden  so you can have any of that so this is one way   the next thing which I want to show you the other  way which we will use is the try and catch so we   will handle the exception using try and catch  all right try and catch and now with this what   I'm going to do is let's write some code so I  will have try and I will call some functions so   let's have a do something function here right now  we don't have the definition of this function so   let's have a catch and inside the catch you will  have the error object and then I will write here   console.log I will type error occur and let's see  what we have in the error as well so I'm going to   type e as well uh let's save and let's try so  I will have a clear and now when I try to run   it you will see that we get an error which is  the error occurred and the error occurred has a   reference error which is that do something is not  defined which is obvious we did not Define the do   something now let's define this do something  function so so what I will do is I will have   a function do something and this will be having  a constant I will have the data which is equals   to the fetch or we don't do anything like that  first what we will do is we are simply going to   have a console log so let's have a console.log  and I am from do function all right I will save   it and now if we try to run it then we are not  going to see the exceptions so if I run it then   we see that I am from the do function or maybe  do something function so I will change this to   do something function but now in case you have the  do something but still that do something when you   call the do something you get an exception and  if we want to generate a exception uh what I'm   going to do is I can create a constant data and  I can use the fetch API and inside the fetch API   I will simply have the localhost 3000 slash API  and in some cases uh it may happen that when you   make an an API call and that is a network failure  or you did not get the data properly in that case   what you can do is you need to throw an exception  to the users and that's where you will be able to   use this try and catch so here what I will do is I  have something issue with my URL which I'm trying   to call in the Fetch and now if I try it then you  will see that we have an error occurred and that   is that fetch is not defined now the next way is  that sometimes you were not able to handle all the   exceptions and you have some uncut exceptions  which you are not able to cut it so for that   what we can do is let's comment this out and the  third one which I want to show you is the uncaught   exceptions so let's have the uncaught exception  so for this uncut exception we can make use of a   process which is a core node.js module so what I  will do I will write the process dot on and here   we can have the uncut exception so I will write  the uncaught exception and we will have the error   all right this will be an arrow function and we  can write here the console DOT log there was an   uncaught exception and we can add the error here  and we can also use that once we get the uncaught   exception we want to exit the flow of the code so  for that we can do the process dot exit all right   and we can have the exact one I will save it and  now let's run it so I will run so I will clear   the console first and let's run it so if I run it  you won't see anything and that is because we are   not doing here anything we have the do something  function but we are not calling it so what I will   do is I will call the do something function here  I will save it and now let's give a try and here   you will see that we have an uncut exception so  this time we did not got the exception with the   help of try and catch so that's where we have  added an uncut exception if you don't catch any   of the exception in your code then it will fall  by default to the uncut exception the next we   can do is we can use the exception with promises  so what I'm going to do is I'm going to comment   this out and I'm gonna have your exceptions  with promises so we can use the promise here   so let's create a promise I will have a promise  and this will be equals to the new promise so   let's create a new promise and this is going to  have two methods which is resolve and reject all   right this is going to be an arrow function and  here I can type that if let's minimize this and   here I will have that if it's false then in that  case I want to reject it so let's have a result   and I'm going to call do something here and if  it's not resolved then it will be rejected since   we have if as false then in that case also I will  have do something here all right I will save it I   will have an else here and I will put this part  in the else all right I will save it and now if   we want to run the promise uh what we can do is we  can use the promise dot then all right and inside   the then we will have the value and here we can  type the console. log and we can have the value   here this will become console.log and we print  the value so if you don't know about promises   well then I have a complete tutorial on it you can  click on the card above and jump to it directly   and in this case if we want to catch the error we  can also have a catch so let me have a catch here   and this will have an error we have the arrow  function and we will do the console.log and we   can have the error occurred and we can also lock  the console error object so let's have the error   all right let's save it and let's give a try so  what I will do is I'm going to remove this we   don't want it here I'll save it and I will run the  application so I have the node error JS and this   is false that means it's going to go to the reject  and when it goes to the reject it's going to call   the do something and when we call the do something  we are going to have an issue here because fetch   is not defined and then it will directly fall  into the error so let's try and run it and now   we see that we have an error occurred and the  reference that fetch is not defined so if we   want to make this as true so let's make it true  and when this is true we don't have this we are   going to log I am from do something function and  now let's give a try so I will clear the console   so let's clear the console first and now I will  try then in that case you will see that we have   an error still and it says that error occurred and  we should not see the error because we have the do   something and we have misspelled this something  I will save it and now let's run it again so in   this case you see that I am from do something  function which is this one and we don't see   anything here and that is because we are not  returning anything from here so what I can do   here is that uh I can have constant data and I  can have this same data so I will have the same   data and I can add the data here and then we can  return this data so let's have a return data and   now this time if I try to run it then we see that  we have I am from I am from do something function   this one and then we return this data which we  are printing it in the value so this is also   one of the way where you can use uh the promises  and inside the promises uh how you can handle the   exceptions the last one in the error handling in  node.js is the async await so how we can do when   we are using the async of it so what I will do  is I'm going to have right here exception with a   sync and a weight so let's see an example so what  I'm going to do is uh I will just comment this out   we don't want this so I will also comment this one  all right and then here I'm going to write a async   function so let's have a constant sum function  all right this will be an arrow function so I   will have an arrow function and here what I will  do is I'm going to use try and inside the try I   will do an update for do something and since we  are using async await so I have to make this as   an async and if everything goes well or then we  will have the try but if there is an error we will   catch the error so let me have the error and here  I can have the console dot error I can write the   console.error or I can also use the throw custom  error and then I can have the error Dot message   all right I will save it and now let's call this  function sum function so I'm going to call the   function here now let's give a try I'm going to  clear the console and I will run the application   and you see that we have I am from something  but in case if this function do something is   having some error so let's go and make an error  here so I'm going to comment this out and let's   show this and now if I run it then we are going  to see an error which is throw custom error and   we see that we have made a mistake so it should  be a new keyword because we want to instantiate   the custom error so let's clear the console and  let's run it again so now you will see that we   have a custom error and we have the fetches not  defined so these are different ways you can handle   the error in node.js with the help of exception  and that is with the error object you can have a   custom error you can also handle the exceptions  using try and catch then you can use the uncut   exception if we have not catch the exception then  it will fall under the uncut exception then we can   see exceptions in promises and in the end we see  how we can handle the exceptions with async awake all right so the next part of the video is uh  how we can manipulate files uh in node.js so   we are going to explore the file system module of  node.js so let's go and let's first check the the   documentation so I'm going to go here and let's  go to the documentation and if I search for a file   system then we should be able to see something  and this is the file system so we are going to   explore how we can use the node.js file system  and the other thing is which is very similar for   this file system is the path so path is also a  core module and is used to manage the path of   the files so this is the other module which we  are going to explore in this video all right so   now let's jump to the example and let's see how  we can use the file system and the path in order   to manipulate the files like reading and writing  from the files or renaming the files all right so   to start with the path and the file system module  what we are going to do is I'm going to create   a folder here so let me create a folder and I I  will have the files and I'm going to create two   sample files so that we can manipulate them so I'm  going to create a sample.txt and then I'm going to   create one more which is a text Dot txt and in  the sample.txt let's have some sample content   and I'm going to add here this is node.js tutorial  series for beginners all right I will save it and   for the text txt I'm not going to put anything  and let's create an index.js file so I'm going   to close everything and I'm going to create an  index.js so I will have the index.js oops dot JS   and now in the index.js what we are going to do is  first let's explore the path module because we are   going to use the path module in our file systems  as well so I'm going to create a constant and we   have a path module which will be required and we  will have the path and now to explore what what   actually this part module is helpful what we can  do is I'm going to create create a constant file   path and now what we want is we need a path  of any of the files so I'm going to go to the   sample let's copy the path and I'm going to add  the path here now if we see the path of our file   is that uses the page Mark via documents code  node.js crash course files and sample.txt and   now with the path module what we can get is we  can get the directory name we can also get the   file base name and we can get the extension of  the file so what I will do is let's first have   the directory name then we will see how we get  the base name and then we are going to see how   we get the extension of the file so here I will  have a console DOT log and we can do path dot   directory name and we can add the file path here  I will save it let's see how we can do the console   log of Base name so I'm going to have the path  dot base name and I'm going to add the file path   so we have the file file path I made some mistake  here and then similarly if we want the extension   we can use the EXT name so let's have this and we  can have the EXT name I will run it and we'll see   what is the output of all this three so I'm going  to clear the console and let's run the index.js so   I will have the index.js and here we can see uh  what we get so if I increase my screen size then   we see that the first console is the directory  name so the name of the directory is still users   till the files so now we can see that the first  console is the directory name uh so the directory   name of our filesample.txt is files so we get the  complete path of it till the directory the second   one was the base name which is the file name and  this is the sample.txt and third one is just the   extension so so we don't see the third console so  let's run it again and here we will see that we   have the third console s dot txt so in this way we  get the directory name base name of a file and the   the extension of the file now there are two other  things which we which I want to show is uh that   we can also do a console DOT log of underscore  underscore name and this is going to give us a   directory name of uh with respect to our project  and we also have a underscore underscore file name   so let's change this and we can have the file name  here let's run it so here you will see that we get   the name as the directory of our project so uh  and in the file name we get the name of the file   which is we are running this application which  is the index.js so these two also we can make use   whenever we actually use the file manipulation  and one more thing which I want to show is the   path dot join we can also join the path so let's  comment this out we we don't want them and we can   see how we can use the path dot join so what  I will do is I will have the console.log and   then I can use the path Dot join and here we can  actually join the path so let's have a path dot   directory name first then I'm going to give the  file path all right and once I have this what I   will do is I want to give a file name so let's  create a simple file name a sample file and this   will be a sample dot EXT and we want to join  them so what I can do is I can here write as   sample file name I will save it and let's give  a try so we see that we have a space here and   that is because we created a join n so we have to  remove this from here and then let's add it here   and now if we run it so let's clear the console  so I'm going to clear the console and now if we   run it then we see that we have the complete path  join all right so this was the sum of the useful   methods of the path module which we are going to  use for the file system as well now let's start   with the file system module so what I will do is  I'm going to comment this out we don't want them   and here what we'll do is I'm going to have a con  constant FS which stands for the file system and   I'm going to use the require and here I will have  the fs all right and now let's do a simple console   log and see what all methods we have on this  file system module so I will do a console log   and let's run this now you'll see that there's a  lot of uh methods like rename the file you will   have the read you will have the read sync you will  have the right and that's a lot of things you can   change the permissions with the CH mode or you can  make the directory uh we are going to see how we   can write into the file and how we can read into  the while so there are a couple of ways you can   read data from the file let's start with the first  one so what I'm going to do is I will have reading   from a file and we have the fs dot read file and  then we need to specify the file path so let's   have the file path here and then what we can do is  whenever we have this it's give a call back which   is an error object and the data that we are going  to read then I can simply have a console.log of   the data all right but if in case of an error  we have to throw an error so let's have an if   there is an error we are going to throw an error  so I'm going to use the error object and I will   write something went wrong now we can run this so  I'm going to save and let's run the application so   I will first clear the console and let's run the  application and you will see that when we run the   application we see some buffer so now to change  this into a readable text what we can do is either   we can use the dot to string here now if I run it  then we will be able to see that this is nodejs   tutorial series for beginners and there is other  way also you can also use the character encoding   so what I can do is I can here pass the UTF hyphen  8 character encoding all right and now if I run it   then you will see that this is node.js tutorial  series for beginners now this way of read line is   the asynchronous way of using the read file now if  we want to do it in synchronous version then what   we can do is we can make use of an FS dot read  file sync and we can pass the file path and we   can also pass the character encoding but now since  we don't want to use the file path I want to show   you how you can use the path module here so what  we can do is we can have path dot join and then we   can use the door name and this durname is going to  give us the directory of this node.js and inside   this directory what we have is we have the files  directory and inside the files directory I want   to use the sample dot txt which is the file name  so this is a better version of using the file path   and not using the whole path we can use this and  since it's the synchronous function it is going   to return us the data so we are going to have the  data here let's wrap this in a try catch block so   I'm going to have a try I'm going to have a catch  which is going to have an error all right and then   I can simply write a console.log of the error  and I will take this cut it and then I will add   it in the catch block I can also use the console  DOT log and I can lock the data I'll save it and   now if we give a try then we see that we have a  buffer but now you will see that uh since if we   see the execution flow first we have this file  read and then we have this file read swing but   since this is an asynchronous it will make a call  and the execution will go on to this and once this   is completely executed because this is going to  be in a blocking nature once this is completely   executed the Callback function will run and we  get the data so that's why you see this being   printed first and then we have the data on this  now here we can also add the character encoding   so if we want to add the character encoding we can  go here and we can add the utf-8 so I will select   the utf-8 alright I will save it and let's run  then we see that we have this is node.js tutorial   series for beginners so this is the asynchronous  way of doing this is a synchronous way of doing   now there is a third way to read the file which  is a file system promises so what I will do is I   will have an FS promise all right and then I will  write the require and this is going to take the fs   dot promise now we can use this FS promise object  to do the breed of the file so what I will do is   I will write a new tribe block and I'm going to  have a constant data is equals to FS promise and   I will just wrap this into function so I'm going  to have a file reading function which is equals   to this will be an async function so I will have  an arrow function and inside that I'm going to use   this and I will have the await here all right so  let's have an update and then FS promise dot read   file so we can have a read file and then inside  this read file I can either use the file path or   I can also use the path in this format so let's  use a file path for now so I will have the file   path and then I need to pass the encoding all  right the encoding is the UTF eight now we have   the data and then now we can do the console.log  of that data so let's have a console log of the   data and if it's an error then we can throw the  error so let me add the error block here now we   need to call this file reading so I'm going to  go here and I'm going to call the file reading   now just for the sake of Simplicity I am going to  comment this out so we don't print multiple times   and I will comment this out as well now let's  give a try so I'm going to run the application   and I see that we have a node.js tutorial so  just for the distinguish I will do is here as   FS promises all right and I will run it again  then we see that we have the fs promises and   we can read it now what we can do is now let's  see on the right how we can write the file so   the one way you can do is obviously you can use  the read file you have a very similar write file   which will have a callback and then you also  have a write file sync so let's quickly check   the example so I'm going to copy this and I will  come here I will write writing into file I will   save this and then I will paste it and instead of  the read file we have the right file this time so   I will have the right file all right we need to  give the path of the file which we want to write   so I'm going to write it in this file the text  Dot txt right now there's nothing in this file   so we are going to write some information here so  let's have a file path so I'm going to create a   constant I will have the text file and then this  will be equals to so what I can do is I can have   here path dot join so let's have a path dot join  I will take the name so I will have the directory   name all right then we are going to have the files  folder and then we are going to have the text   dot txt all right now we have the path now we are  also going to create a constant for the content   which I want to write in this file so I'm going  to write I love this node.js tutorial Series so   this is the content we want to write into the file  so what we will do is first we have to specify the   file where we want to write so I'm going to have  the text file here and then this is going to have   an error and this will not have any data because  it's not going to return anything we are going to   pass the data here so I will have the content here  now it will throw an error if something is wrong   while writing into the file and we will have the  data here so what I will do is I'm going to write   here uh write operation completed successfully so  we will have this log once the right operation is   done successfully so now what we are going to  do is let's go in let's try it so I will have   I will just clear the console first so that we  see a clean console so let's clear it out and   now let's run the application now you will see  that we have the fs promise because we are still   calling this file reading function but we have a  write operation completed successfully that means   the content I love this node.js tutorial series  is now actually returned into the content so if   I go and check then you will see that we have the  content in our file now very similar we have the   right file sync which is asynchronous version of  writing into a file so I think we we don't need   to cover that you can easily try this one that  we have a very similar one this and you can just   change this to write file sync but the interesting  one will be that if I write this content in the   file and after writing I want to read the same  content so for that what I can do is uh I will   come here all right and now I'm going to read it  from here so if I want to read it what I will do   is I will have FS dot read file I need to specify  the file name all right I need to specify the   character encoding and then this is going to give  me an error and the data and then here I will have   the console.log of the data I will save it and  we can have an if there is any error then we just   have to throw the error and I will have the new  error and I will write the error here all right   now you will see that we have a callback function  inside one more callback so first we do the right   operation and then we do the read operation so if  I want to go and check for that what I will do is   I'm going to remove this because otherwise it's  going to write twice in the same file now if I run   it then we get an error because we did a mistake  okay we will just fix it let's clear the console   and let's run it again then you will see that  we have write operation completed successfully   and then I was able to read it but since now if  you want to do multiple operations like you read   a file then you write a file and then you append  the file then in this case this will become very   tedious because you will have a lot of callbacks  so a better approach is to use the fs promises   so let's rewrite this in the same way in the fs  promise so what I will do here is that constant   writing in file all right this will be an arrow  function and then what we can do is I will have   the fs promise dot write file and here what I want  to write is first I will give the file name so   let's have the file name text file then I'm going  to pass the content which I want to write into the   file and now when I have this what I want to do is  I will make this as a sync and let's have an await   here we have the async of weight and then after  that what I will do is I want to append the file   so I will write some data into it and then I'm  going to append the file so let's have an append   function here so I will have the fs promises and  simply the same way we have a read file we have   a write file if we want to append the file then  we can use the append file so here I'm going to   do the append file and it is going to add the text  in the end of the file so here here what I will do   is I'm going to have the same file name so text  file and then we need to provide the content so   I will have slash n this is file appender I will  save it and once we do all this thing I want to   read the data so I will have a data I will have  the fs promise and then I will have the read file   I will read file as text file then here I can do  the console.log so we will take all this into a   try catch block so that in case of an error we can  catch the error so I will have a try block inside   the try block I'm going to cut this I'm going to  add this here then we can have a catch and we can   have the error and then we let's do a console  log of the error so I'm going to have the error   here I will save it now you will see that this one  it's more neat and clean so I have to add an await   here as compared to this async way of using  the callbacks so it's it's always recommended   that we use the fs promises because it's more  cleaner way and it's easy to read so now let's   comment this out we we are not interested in this  and if we go here then we see that we have some   information here so I'm going to remove this as  well now I will clear the console and now let's   try so I will hit enter and we see that we have  only one information which is the fs promises and   which is this one and that is the reason because  we did not call this function so let's call this   function first so I will call this function here  all right so now we also need to print this uh   once we read the data we need to print that data  so I will have a console.log and let's print the   data I will save it now let's give a try so what I  will do is I'm going to run the node index.js and   here you will see that we have FS promises we also  read the information that means we have already   written the content in the text file and we also  appended the file so if we go here we see that I   love this node.js series and then we have this is  the file appender so this is because of this file   append so uh what I will do is I will just do a to  string all right I will save it and now let's give   a try then you will see that we have I love this  node.js tutorial series and then this is the file   of pendant now if you don't want to append the  file and you want to write something at the end   of the file so in that case what I can do is uh I  will just comment this out and here while writing   the file so what I will do is I have this two file  and I want to add more information after this so   in this case what I will do is I'm going to add  a flag here and I will just change the content   that slash n and here I would write it's awesome  and now what I will do is I'm going to add a flag   here and I will give the flag as a plus so this is  going to take my position of the head at the last   of the content so it will go and it will place it  in the end and then we can write whatever we want   to write it so I will save it and let's give it  try so I will run this and now you will see that   we have I love this node.js tutorial Series this  is file upender and it's awesome and because of   this a plus flag we can actually take the the head  position at the end of the file now the last one   I want to show you is how you can rename the file  so if I want to rename this file instead of this   text what I want is I want to rename this file  so in that case what I can do is let's add it   here so I will rename the file first and then  I will read it from the file so so I will have   the await here and then I will have the fs dot  promises dot rename so we can use the rename and   then we can give the path so the first path which  I want to give is the text file and then the new   file name which I want to give is let's give a new  file name I will have the path dot joint first so   let's have the path dot join then I will give the  door name I will give my files folder and the new   file name which I want to give is new text so  I will have the new text Dot text I will save   it all right and once I have this after are giving  a new name I want to read it from the new name so   I will copy this and I will add it here I will  save it and what I want to append is I want to   say that we have given new name to the file I will  save it now let's give a try so I'm going to run   this and you will see that I love this node.js  tutorial Series this is file upender awesome we   have added a new text which is we have given a  new file and then in the end we have read this   complete file now if we go here and check then  we will see that we have the new name of the file all right guys so first we will try to  understand what this synchronous code is   and how the synchronous code execution happens so  I'm just going to write some console DOT log and   I'm going to do task one all right and I will copy  this so I'm going to copy this and I'm going to   do here task 2 and task three and if I save this  then we will see that the execution will happens   sequentially so first the task one will be logged  and then tasks 2 and then task three and that is   very obvious so this is the synchronous execution  of the code one code is executed after line by   line but there are some of the tasks which you  see that that actually blocks your execution and   such tasks are like if you want to call an API and  you never know that how much time the API going to   take to respond you back and in such cases the  execution of the code will stop there itself   until you get the data back from the server and  there you can see that there is a blocking code   because the error execution will halt until you  get the response back from the server so let me   create an example which actually shows us the  blocking code so what I'm going to do I'm going   to write a console.log and I'm going to like log  here start operation all right and then I'm going   to write a function sleep and it's going to take  an argument milliseconds and then I'm going to   create a variable star time and it's going to take  the current time so I'm going to do get time all   right and then I'm going to create a while loop  here so that while loop will be taking the new   date dot get time all right and if this time is  less than the start time plus the milliseconds   which I am going to pass into my function so I  will add that millisecond and before adding this   what I want I need to have one more console log  here so I'm going to add a console log here and   I will write here operation is running all right  and then inside this I'm going to console DOT log   in progress and the last I'm going to console  here operation is done all right and once this   operation is done then we will do something so let  me console here that two thing else all right so   now let me walk through this code what actually we  are trying to do let me call this leap here so I'm   going to call the Sleep here and I'm going to pass  1000 milliseconds which will be the one second so   what actually we are going to do here is we are  trying to create a delay of execution of our   code so what is going to happen first it's going  to log this start operation and then the function   sleep will be called when this function will  be called we are actually taking the time of   that part and after the time this operation  is running will get executed and then this is   going to be in a while loop until this condition  is satisfied the execution of the code which is   this console this console and the last console  is going to get blocked and the execution once   done then only the execution of the other code  will happen so let me show you if I save this   so now if I start you can see that first we have  the start operation then operation is running and   then it's trying to execute this condition and it  is going to block my execution of the rest of the   code until this condition is satisfied and this  is called the synchronous programming where your   code gets blocked until it's get executed and then  the remaining code will get executed so this is   the blocking code so this can be sometime lead  into a bad user experience because when you do   a synchronous code you cannot write a performant  application let's understand this with some slides   so when the synchronous code execution happens  what is actually happening under the hood so under   the hood the JavaScript runtime engine consists  of two parts the first part is the Heap where   the memory allocation happens and the second part  is the call stack which is a single thread which   the JavaScript browser has to in order to execute  the JavaScript code so in the calls tag you will   see that there will be a global execution context  which is you can say as a main method and we are   going to take the same example which we saw in  our Visual Studio code so you can see that we   have the same example here and the code execution  will happen line by line starting from the first   console log which is the start operation so the  start operation is now coming into the call stack   and then in the call stack once it gets executed  we are going to see it on the console browser once   it is done the next step happens is the function  call of Sleep Method and when the Sleep Method   comes into the call stack it's going to call the  function sleep and inside the function sleep we   can see that we have a console log which is the  operation is running so in the next step what   will happen there will be an another stack will  be added on the sleep and that will be the console   lock operation is running once this console log  is printed on the console the next execution will   happen for the while condition so the while  Condition it's going to Halt our execution   until this condition is satisfied that means the  rest of the code execution will be blocked here   so once the condition is satisfied you will see  that the console log in progress is now in the   call stack and once the in progress is logged  into the console the next execution will happen   of the operation is done and that will come into  the call stack and once this is executed we will   see on the console log and now our Sleep Method  is executed completely so it will be removed out   of the call stack and in the end we will have  a console log which says do something else that   will get executed and we'll see it on the console  browser so this is the sequence which we actually   saw in our console when we executed the code in  the visual studio code so let's go back to the   visual studio code and then let's try to convert  this synchronous code into an asynchronous and   then let's see how actually the JavaScript engine  will handle the asynchronous task because it only   has a single thread which is the call stack then  how it's going to handle these async tasks and how   it's going to make our code into a non-blocking  code execution so let's get back to the visual   studio so now we can see that the same sequence is  consoled in the browser now let's try to convert   this synchronous code into an asynchronous I am  just going to remove this part and I will also   remove this as well and what I'm going to add here  I'm going to add a set timeout function which get   executed asynchronously so I'm going to write a  set timeout and the set timeout function actually   accepts an another function as an argument and  that function is known as the Callback we are not   actually going into the deeper part of callback  promises a sync a weight which are the way you   execute your code in an asynchronous manner we  will be seeing these in the coming videos but   now let's just focus how this execution happens  and how this a synchronous task is handled so I'm   going to write if Arrow function here and that  Arrow function is going to do a console.log and   now I will just shift this console here and this  execution will happen uh with some milliseconds   or with some delay which we are going to pass  from our sleep function all right and now if I   save this function the execution I just want you  to think for for some some seconds that how this   execution sequence will happen we obviously  know that the first execution will be the   start operations then the Sleep Method will be  called and once the Sleep Method is called the   browser will execute the console log operation  is running and after that it comes to the set   time out but this is going to be an asynchronous  execution it will not wait for the one second in   order to finish this execution of the set timeout  it will just go on to the next statement which is   the console log do something else and once this is  printed so now if I save it then you will see that   first the start operation happens then operation  is running and then do something else and once it   is get executed it actually prints the operation  is done so this is in an asynchronous manner so it   is not waiting for a set timeout to get executed  and then goes to the next statement unlike what   we saw in the synchronous where it actually  blocks your execution flow until the condition   was matched so so that's the difference between  the async and asynchronous now let's see actually   how this asynchronous thing happens in a single  thread because we only have a call stack so let   me get back to the slides all right so now we are  back into our slides and we have the same example   which we just saw in our Visual Studio code and we  have very simple structure we have a call stack we   have a browser console so the first thing happens  is the start operations comes into the call stack   and after that it's get executed the sleep method  is called now the Sleep Method is in our call   stack and after that the console log operation  is running is coming into the call stack and once   this get executed it gets printed on the console  and then we have the set timeout and here the CB   refers to the Callback function which we pass  the arrow function thousand is the milliseconds   we passed so what happens actually the call stack  immediately as soon as it sees that a set timeout   is in the call stack it will just pop out the set  timeout and it actually gives this set timeout to   the web API so the browser already have this web  API a separate thread which is actually going to   execute your sync functions like set timeout set  into wealth or event listener so all such callback   events or the functions whenever they enter to  a call stack the call stack actually sends them   to a web API for a separate execution thread so  here we can see that the set timeout is in the   web API and next what is going to happen the do  something else will get into the call stack and   once it is printed on the browser the web API  what is going to do is set timeout function   will register itself into an event table in the  web API and once it is registered into the event   table the next thing is going to happen is the  event table will put this callback function into   a task queue so all the Callback functions like  the set timeout set interval add event listener   or Ajax call so all such asynchronous tasks as  a callback function and that callback function   is passed to the task queue once it is passed to  the task queue it will wait for the call stack to   get empty and all execution gets finished now  we can see that the call stack is empty what   is going to do there is a thing called event  Loop so all the events from the task queue are   now passed to the call stack and now our execution  of the Callback function is done by the call stack   and we get sprinted the operation is done so this  is how the under the hood the async execution   happens because call stack is a single thread and  on a single thread we cannot perform the ursync   task so that's how we saw how the asynchronous  execution happens in JavaScript so let me get   back to the visual studio code all right and  this is what the sequence we actually saw when   our execution happened by the JavaScript runtime  we saw first start operation then operation is   running do something else and then we got the  operation is done so that's all we have we know   that how the execution is happening in JavaScript  and how JavaScript handles the asynchronous   task with a single thread and I saw a lot of  developers when whenever you just ask them is   Javascript a synchronous or an asynchronous they  promptly will answer me that it's an asynchronous   but no JavaScript is actually a synchronous  single threaded language but you can handle   the async task using callback promises a sync  await which we are going to see in the next videos all right guys so let's understand what is this  callback function we know that there are regular   functions which we usually write in our code but  then what is this special function which is called   as a callback function so a callback function is  a function which is passed as an argument into   an another function and the other function will  execute this callback function at later point of   time so whenever I say a callback function most of  the JavaScript developers they think that we are   talking about the asynchronous task but that's not  the case because callback by themselves are not   asynchronous they are synchronous in nature and  let me show you that with an example so what I'm   going to do I'm simply going to write a function  async task all right and we are going to pass a   another function which I am going to represent  as CB as callback and then I'm going to call this   callback function at later point of time now the  next thing I'm going to do is I'm going to call   this function and while calling this function  I need to pass a function as a callback so I'm   going to do a arrow function and I'm going to  do a console.log and I'm going to pass name all   right and then I'm going to define the name here  as the page all right for I save it I want to do   some more console log here so I'm going to do  console.org task start all right and I will be   adding one more console log here which will be  task running and the third one I want to do is   Task n and before I do this let me write the page  here directly okay and if I save it now then you   will see that it's very obvious first we are going  to console the task start then the console will   happen for the task running and then the console  will happen for the page and then the task add but   there's no a synchronous part here everything is  happening in a synchronous mode all right the next   thing about I'm going to do is now I'm going to  change this the page to name and as we know that   a lot of people think that callback is an  asynchronous but now if I save it I want you   to think that what will be the execution is the  execution will still be the same or not and if   I save it then you will see that I'm getting  an error and why is this so because callback   are asynchronous and then why it is giving me  an error why it's not able to find the name   here and that is because callback themselves  are not asynchronous they are synchronous in   nature we have to make this callback function  into synchronous mode so that the complete   Javascript file is compiled first and all the  variables are allocated to the memory and then   our callback function is called so in order to  change this function into a callback function we   need to use something like set timeout so let  me use a set timeout here so I'm going to use   a set time out all right and this set timeout  is going to take two arguments one will be the   Callback itself and another I'm going to add a  zero second so the zero second is a very small   all amount of time 0.000 something I just need  to act sometimes so I'm adding it zero and now   if I save it then a function will get executed  properly and now you will see that this callback   function is taken out from the execution flow  and then the complete JS file is compiled all   the variables have been allocated into the memory  and then my callback function is called so in this   way you actually convert your callback function  into an asynchronous execution there are other   ways also doing this you can also use promises  you can use async await if you want to do a   async execution task but let's keep them aside  let's focus more on this callback the another   thing I want to show you is what is a good way  of handling the errors on callback so there's   no specific standard of handling the errors or  there's no a specific way of writing it but when   node.js came out we usually started writing the  error as the first argument in the Callback and   let me show you what is that so I'm just going to  remove this and I will also remove this and this   and the next thing I'm going to do is I'm going  to add the arguments in my callback function so   the first argument is the error and the second  argument is the data all right and let me add   this all right and now the next thing we can do  is if we have an error then we can just simply   throw the error else what we can do we can just  console log the data which is we are getting as   a data here so so that's it I mean the Callback  function will always have the error as the first   argument and the data in the next argument  so that's how I mean you can remember that   when you use a callback you will always get the  error as the first argument and you get the data   that's how from the node.js it started that this  is called the error first callback so now if I   want to pass this uh error so what I'm going  to do is I will just create a function in my   set timeout so I I created an arrow function and  it will still be the same and now when I call my   callback function there is an error I can pass  the error and this error will be taken as the   first argument now if I save it then you will see  that I get an error in my console but if you don't   have an error and you need to have a data you have  a data then your first argument will be passed as   null because you don't have an error and your  second argument will be your data this is the   data ROM server and if I save it then you will be  able to see that now I can see the data so I mean   this is one of the standard way usual practice to  handle the errors on the Callback we use callback   functions very frequently while writing a node.js  application the other thing I want to show you is   now what is this callback hell so we know the  Callback we know the Callback functions how it   happens in the asynchronous mode but what is  this callback hell actually so this callback   hell is a very interesting topic which gives  you an idea about are understanding with the   async Callback functions so in if we are using  the Callback functions and they are executing   in an asynchronous mode but you have that your  logic of sequences should be executed one after   the another in a sequential way then how you're  going to achieve this so if this code execution   was a synchronous mode let me show you with  an example so what I'm going to do is uh I'm   going to remove this and I'm going to write a new  function called May API call and this is going to   accept a callback all right and then I'm going to  use the same timeout function and it will be an   arrow function will be executed in 0 seconds and  I'm just going to do a console.log this is async   Task execution all right so so now the thing is  that once my callback function is get executed I   need to make an another call so in general you can  think about that in in real projects we have have   a lot of scenarios where we actually make an API  call and then once we get the data back from the   API call we need to make an another API call and  how this if this is in a synchronous mode then it   will be a very easy so you we just need to have  like we will be having log this this this so all   this will happen in a very sequential way so the  first line number 12 will get executed then line   number 13 then 14 and 15. so it was very easy  if the code execution was in a synchronous mode   but if the code execution is an asynchronous mode  then what we will do we are first going to call a   make API call all right and this is going to take  a arrow function all right I'm just going to give   an empty Arrow function just for the reference  and now once this callback function is called   I need to make an another API call so what I'm  going to do I need to make an another API call   all right and once my second API call is get  executed I need to perform some other tasks so   let me perform an async task here so I'm going  to write an async task which I want to be in an   asynchronous mode and once it is done I need to  make an another task I need to make an another   task and this way this nesting happens and when  you have a multiple nested callbacks it results   into a callback hell and why is it so we call  it as callback health because now you can see   that it's a very nasty code syntax I mean you need  to remember that this syntax get close here this   syntax get close here this syntax that close here  so I mean in the mind you need to remember a lot   of sequence and and it's not that much readable  so what we are doing here is that we are doing   an asynchronous execution call with a chaining  of callbacks and then we end up with the nasty   syntax of the nesting of callback functions and  which is very hard to understand and readable   and this is called the Callback hell so in order  to do these type of executions or in order to do   these type of logical or chaining of the callback  or chaining of the asynchronous tasks then we you   usually promises or async await which actually  have a more better way of writing the code and   a very simpler to understand so I guess  that's all we had for this callback and   the Callback hell I hope you understand this  uh core nature of this callback and callback   hell how they works and how we convert a  callback function into an async execution all right guys before we jump into code I just  want to explain you what are promises in a very   Layman language so a father promises to his son  that he's going to give him a car if he scores   90 percent in his academics now this there  can be two possibilities either the father   fulfills the promise to his son which is called  the resolve or he failed to fulfill the promise   which is called reject all the fail and very  similarly in JavaScript also we have promises   which takes two arguments either it's a resolve  or it's a reject so let me show you this with an   example so I'm going to create a constant promise  and in order to create a promise in JavaScript we   use new keyword and then we write the promise  and This Promise takes a function which has   two arguments so I'm going to create a function I  will be using an arrow function and it will going   to take two arguments the first argument will  be resolved either the promise is resolved and   the second argument will be the reject and then  we form some operations so let me perform some   operation I'm going to do a console.log and I'm  going to write async task execution and then we   can write some conditions here that if this async  task execution is fulfilled which is true then   that means the promise is resolved so I'm going to  call my resolve method but if it is not resolved   and it gets rejected then I'm going to call a  reject method which is this reject method and   that's it this is the simplest form of a promise  in JavaScript so now next question is how do we   interact with this promise so in order to interact  with this promise we simply use the promise dot   then method and using the dot then method it  accepts two functions the first function is   called when the promise is resolved and the second  function is called when the promise is rejected   so we can use two functions so I'm going to use an  arrow function here and then I can have an another   function which is for the reject all right so now  I have two functions and now let me add a console   DOT log and I'm going to write a success or let me  use past pass all right and similarly I can write   the another console here and that console will  be paid and now if I save it then you will see   that my console log for a sync task execution  is logged and we have made a condition of true   which gets satisfied and my result is called and  whenever the result is called the first method in   the then function will be called and that is the  console log passed but what is the case is that   this promise is not resolved it got rejected so  in that case I'm just going to do a false and if   I save it then it's going to give me failed so in  this case the promise is failed we can do one more   thing here instead of passing this here B we can  actually pass the values from the resolve method   so just take an example that you made an API  call and that API call is now success and that   API call has given you some data so I'm going  to write some data here person and this person   have a name property and I'm going to say the  page all right and I will pass this person as   an argument in the resolve method all right and  let me create here another constant as an error   and this is going to have error code I'm going  to give 1001 and I will pass the error in the   reject Method All right so if I want to use the  value of it then I'm just going to use a Val as   an argument here and I can simply log the console  here and now if I save it then you can see that I   get the data which is being passed in the resolve  method similarly if you if your promise is not   resolved and your promise is rejected then you can  simply take take the argument as error and you can   type the error here and this is going to give you  the error I want to show you one more thing that   with this then you can also make a catch of your  error so if I want to catch the error I'm going   to write simply catch and this catch will have a  arrow function and I'm going to do a console.log   failed all right and if I save it then you will  see that I am not able to see the fail is because   I have an another function in my then which is  the error function so what happens in case you   have missed the error function in your then method  then it's directly going to call the catch method   now in this case you will see that the promise  is rejected and a error is thrown and an error   is handled in the catch section and you can also  use finally here finally and this is going to take   a arrow function and I can do a console.log  and let me do some cleanup so this finally   will always be called when you interact with the  promise so it's going to give me the fail but it's   also going to call the finally method you can  do one more thing that if your promise throws   an error then you can actually write the throw  an error and what is going to happen is when you   actually throw the error it's going to call the  reject method by default so when you throw the   error it's going to automatically being cached in  the catch function and if I directly write here   then it's going to give me an error and that's  where we are getting the error so this is a case   where you actually had a promise and which is  immediately resolved or rejected but there may   be a case that you have a promise which is being  already resolved and now you want to interact with   it so you can also do that and let me show you  the example so I'm going to do a let e and we   have a promise which is already being resolved  the promise is already being done so I can do   directly promise dot resolve and I can into the  execution is done so this is a promise which is   already being resolved and if I want to do the  reject then I can similarly do the reject as well   so I'm just going to copy paste and I'm going to  change this reject execution is rejected so now   even though the promise is resolved we can still  interact with using the then Handler and this part   we cannot do in the Callback functions once the  Callback function is executed you cannot attach   anything to it or you cannot interact with it but  that's not the case with the promises and that's   where the promises has advantages as compared to  the Callback functions so what we can do is if I   want to interact with it I'm just going to write  P dot then function and I can do the console.log   well and I will pass the well here all right  and now if I save it then you will see that   we get the execution is done as a console log  but this was not possible if we have used the   Callback functions next thing I want want to show  you is that promises are by default asynchronous   in nature whereas we saw that callbacks they  are not asynchronous by default we have to use   set timeout function in order to make it as  a asynchronous execution so let's go to that   example again so this was the example we used in  our callback functions video and if I save it then   we know that we are going to get a reference error  because callbacks by default are not asynchronous   now let's convert this into promise and let's  see that so for converting this to promise I'm   going to remove this and I'm going to return a  promise dot resolve all right and then what we   are going to do is I'm just going to remove this  Dot and this is going to have an arrow function   and I'm going to do a simple conceal.log name and  now if I save it then you will see that the code   execution happens so that means the promises are  asynchronous in nature they are taken out out of   the execution flow and then execute it later  on so that's why we get the variable name as   it's already being allocated in the memory and  JavaScript runtime engine will be able to give   us the value name the next thing I want to show  you is how we can do chaining in promises we saw   in the Callback functions that when we have to  do the logical sequence one after the another we   result into the nesting of callback functions and  which gives us the Callback hell so let's see how   we actually do the chaining in promises so I'm  going to write a constant B and that is having a   promise which is resolved just for the sake of  Simplicity all right and it's resolve and I'm   going to write done and now I'm going to write  P dot then it's going to take a argument and   then I'm going to console DOT log and I'm going  to print the value all right so we know that we   are going to get the value as done but now once  this promise is resolved I want to make a chain   I want to make some another execution then what I  can do dot another then and I can repeat the same   thing I can do a console.log but usually when you  use chaining in promises every then Handler has   to return something so that the other than handle  will accept it so if I want to do that I need to   return something from here so let me return as  done too and this done too will be accepted as   an argument by the other then function and then  I can do the vowel and now if I save it then you   will see that we have done and then we have done  two and if I want to continue this chain then   return 3 then and I can simply console.log so I  will accept the well and I can do the console.log   well and now let me save it so now you can see  done done to done three but if you do not return   anything from the then method then your chain will  get break so you always has to return something   and some Suppose there is a case that you have an  error so let me do this as a reject all right and   I'm going to do a fail that unlike the callbacks  where you have the error first callback you don't   need to write the error method in each of the then  method so what I'm going to do uh either I can   directly write a catch in the last then I can do  the console.dog well well I save it then I'm going   to get the fail so that is one of the advantage  that this code is more readable and understandable   by the developers as compared to the one which  we saw in the Callback hell the last part I want   to show you is the promise all and promise raise  so I'm just going to remove this and I'm going to   write a new function I'm going to write a make API  call and this function going to return a promise   so I'm going to return a promise you promise and  this new promise will have two arguments the first   argument will be the result and another argument  will with the reject all right and next thing what   I want to do is I'm going to write a set timeout  function here so I'm going to write a set timeout   and what I want that this API call will accept a  parameter as time so I'm going to use that time   here and then I'm just going to do a result and  I'm going to write here this API executed in plus   time seconds now let's try it so I'm going to call  this API and I'm going to pass 1000 milliseconds   so it's going to take one second in order to  execute this API then I'm going to pass a Val   here let's have the arrow function and then I'm  going to do a console.log and I'm going to log the   pal all right and now if I save it then you can  see that after one second my API get executed so   that's we understood now there is a scenario that  we want to make multiple API calls and all those   API calls should go simultaneously we should not  want that first one API call will be executed then   the second one then the third one so how we can do  that what I'm going to do I'm going to remove this   and I'm going to make a constant and I'm going  to write multi API call all right and I'm going   to pass an array so the first API call is going  to take 1000 millisecond second API call is going   to take 2000 milliseconds and the third API call  I want that it's going to take 500 milliseconds   all right so now I have created a variable multi  API which is an array and it's going to call three   times the make API call so what I want I want to  interact with all the promises only once all the   execution of the API is done so what I can do for  that is I can use promise dot all and in the dot   all I can pass the multi API call and then I  can use dot then and this is going to return   me the values so it's going to return me the  array of values and I'm just simply going to   consult DOT log values whatever values I have been  returned so it's going to return me the array of   values so now if I save it then you will see that  I'm getting an array of the values we have three   promises got resolved the first one API executed  in Thousand millisecond two thousand millisecond   and 500 millisecond and believe me these all  three API calls were simultaneously they were   not waiting for one to finish and the another one  they all went through simultaneously so if if we   want to see that why the sequence is thousand  two thousand and five hundred if we want to see   because we know that obviously the one with the  500 millisecond will get executed first because   it's going to take the less time and if we want  to see that we can see that as well so what I'm   going to do I'm going to use promise dot raise  so the race is going to return me first promise   which is being resolved so if I do the same thing  again all the API call Dot then it will not return   me an array it's simply going to return me a  value and then I'm just going to do a console   DOT log and I'm going to print the value all  right and now if I save it then you will see   that I only get one value which is among the  three API calls which got executed first and   if you save it then you will see that this API is  executed in 500 seconds and that is very obvious   because that is the API which is going to take  the minimum amount of time so that's all about   the promises that you should know while writing  your projects and Promises is one of the very   important Concepts in JavaScript whenever we  are dealing with the asynchronous programming all right guys so I already have two functions  user login and go to home page let me give you a   walkthrough of these functions so the user login  function prompts for username and password and   once we add the username and the password it  returns a promise and This Promise contains   a set timeout function just executed after 1000  milliseconds and the set timeout function actually   checks for the username and the password if they  matches the promise is resolved and if it fails   the promise gets rejected if you don't know about  promises and how to interact with them I have a   video on it you can click on the card above and  jump to it directly so the second function which   is the go to home page accepts the user auth  status so once it gets the user or status it   returns a promise which is always resolved with  a message go to home page and we add the user   auth status now let's see how we can call this  function and interact with the promises first   and then we are going to do the same thing using a  sync await and we will see the difference between   the promises and using a sync await function so  what we are going to do I am going to call this   function as user login and we can call it using  dot then and when the promise is resolved it's   going to give me a response and this response will  be the user authenticated so what I'm going to do   I'm going to write a console.log here and it will  say validated and once the user is validated we   are going to call the other function which is the  go to home page and we will pass the same response   to go to home page so this go to home page will  also return a promise so we can interact with the   promise using chaining in promises so I'm going  to write a DOT then and this is going to have the   response which is going to return so I'm going to  add here user auth status and in order to get the   response we need to actually returns function  so let me return this here and here we are just   simply going to do a console.log and we are going  to log the user auth status all right so now let's   save it and let's see what happens so if I save it  it's prompting me for the username so I'm going to   write the page as username and I'm going to add  the page as password and if I hit enter then it   says that user entered username and password  first then performing user authentication then   validated user and yes the promise is resolved  so we are actually seeing that go to home page   as user authenticated so the user authentication  is done and that's why we are going to go to home   page but what if the authentication gets failed  so let me refresh this and this time I'm going   to add actually some other name Niche and I'm  going to add the page and if I hit enter then   it says that performing user authentication but  the authentication is fail and we can actually   handle this error using dot catch in promises so  I'm going to add dot catch here and this is going   to take an error so I'm going to add an error here  and I'm going to add console.error all right and   this time if I write page then it's going to say  that authentication fail which is very correct   so there's nothing wrong with this approach this  is very good approach using promises but you can   actually write it in a more concise and more  readable form you don't need to write dot then   dot then again and again so what we can do is  we can switch to a sync await now let's see how   we can write the same thing in async await in  a very short of syntax and in a very readable   way so I'm going to comment this out so when you  use a sync await you actually need to wrap your   async execution into a function so you can use any  function a named function and function expression   or if you want you can use a self-executing  function so what I'm going to do I'm going to   write a function perform task and we need to use  async await so we need to add a keyword here a   sync and then what we will do we are going to  first call the user login so I'm going to call   the user login and this user login function is  actually going to return me some response based   on the promise get resolved or reject it so I'm  going to capture this response in a constant all   right and we are using a sink of it so we actually  need to add an await keyword here so that we have   to wait for this function get executed and now  once we get the response what we are going to do   we are going to do a console.log and this will  say validated user all right and after that we   are going to call our go to home page method so  for that I'm going to add go to home page and   it's going to take the response and this is also  going to return us a promise so we need to add   an away keyword here as well and we are going  to capture the response in a constant and I'm   going to add the user or status is equals to away  all right so now we have captured the response of   go to home page now we are just going to do a  console.log user auth status all right and now   we just need to call this function so I'm going to  call the perform task and let's see what happens   so I'm going to add the page I'm going to add the  page as password and if I hit enter then we can   see that we are getting the same response which  we are getting in the Promises part so we have   the enter username perform user authentication  user validated user and go to home page as user   authenticated so this syntax is much more concise  and more readable as compared to the user login   so this is one of the advantage of using a sync  await that it adds a syntactic sugar which makes   your code more concise and more readable and what  happens in case if you get an error so if I enter   wrong credentials so in that case it's going to  give me an uncut error authentication failed so   we can actually handle the error in async await  with the try catch so what I'm going to do I'm   going to add a try here and then I'm going to do  a catch and we can add all our execution code in   the try block so I'm going to cut this from here  and I'm going to add this here and in the catch   we can simply add an error so if we have an error  we can do a console.log and we can log the error   and now if I save it and now let's see I enter a  wrong username and password and we will be able   to see the error so that's how you can actually  handle the errors in while using a sync await but   you have to be very careful while using the async  await you have to use the keywords properly so if   I create a function without using a sync and  I have an await then it's going to return me   an error or if I missed out an await and I simply  use an async function will still get executed so   I'm going to add the page I'm going to add the  page the function will still get executed but   it is going to return me a promise so you have  to write the await in order to get the async   await function properly so I have to add an await  here and I have to add a weight here all right so   that's how you use the async await which are  more better in terms of writing the syntax   as compared to the promises now let's talk about  the performance is using await a more performant   or a promises is more performant and let me show  you the example which we used in our promises   video so let me copy paste that example so this is  the example we used in our promises video we have   a function make API call which accepts a time and  then function returns a promise and it contains a   set timeout function which will be executed after  the time which we passed in the function and it's   going to resolve the promise the API is executed  after particular time and then we have an array   of API calls so we make an API call at 1000  millisecond two thousand millisecond and 500   millisecond and if we want to interact with all  these promises at the same time we use promise   dot all and this is actually going to return all  the promises based on the times so the execution   of all these API calls start simultaneously so  it's not that one is executing then the another   then the another but what if we want to change  this into a async await so what I'm going to do   I'm going to just comment this out and I'm going  to use an anonymous self-executing function so   I'm going to write a function here all right and  this function is will be self-executed and inside   the function I'm going to do a 4 let's use a 4  off so for off I'm going to use a let request of   API requests and inside that I'm simply going to  do a console.log I'm going to write a weight and   I'm going to execute this request so I'm going  to execute this request and we need to return a   function instead of returning a promise so let's  return a function from here all right and now if   I save it then you will see that the execution  happens one after the another so that's how the   performance varies when you use promises and when  you use a sync await so when you use promise dot   all all the API requests and at the same time and  it got executed based on this but in the case of   an async await it will wait for the execution of  each API and then it's going to execute the next   API so when you use a sink of weight there are  some drawbacks which you need to take care so   if you can have a proper mix match of promises  and async await then you can actually write a   performant application but just replacing promises  with the async await throughout your project   is it's not a good approach as you will have a  good readable code but you are actually going to   decrease the performance of your application and  JavaScript is all known about its performance and   fast application and fast execution so you need  to be little bit Careful by using async await all right guys so before we start building our  crud API project let's understand something about   the restful conventions so this is the restful  API convention we are going to use we have the   crud actions like get all movies where movie is  the resource that we are going to build then we   have the get movie if you want to get an  individual movie then we have the create   movie update movie and delete movie and the  HTTP methods we are going to use is the get   put post and delete and on the extreme right  we will see that we have the end points we   will have the slash API slash movies which is  a resource name and then for the other cases   like get put and delete we are going to pass  the ID for the individual movie so now let's   start with the installation of the node.js so I  have already covered this in my previous videos   so if you have missed that then you can click on  the card above and jump to it directly so I will   go to the visual studio code and I have an empty  project which is the node.js crud API now what we   are going to do is first let's create the packet  Json file and make sure that in this project we   are not going to use any of the framework or the  library or middleware we are going to build it   with pure node.js all right so I'm going to go  to the terminal and inside the terminal what I   will do is I'm going to create the packet Json  file so let's have the npm in it and now it's   asking me for the project name I'm going to give  the project name as node.js crud API project all   right I will have the first version and I will  write this as vanilla node.js crud API project   then for the entry point I will give as index.js  which is default we don't have any test command   no git repository no keywords author will be  the page malvia so let me have the page malvia   and then I'm going to click yes and then it's  going to give me the package.json file now the   only package which we are going to use is the node  Mon and the dot EnV so let's install the node mod   first so I'm going to install npm install hyphen  hyphen save hyphen Dev node mod so this node mon   will automatically restart our server whenever  we make any changes now the other thing is we   can also install the dot EnV because if we are  going to create any environment variables then   we can use them with the help of the process code  all right so I see that we have the node mon we   also have the dot EnV now the next thing we will  do is let's create the index.js file so I'm going   to create here index.js all right or eventually  let's rename it as server.js so I will have it   server.js if I go to my packet Json I have the  node Mon and here what I have to do is I will   just change this to server.js and I will add a  script for uh starting my applications so I will   have the start and to the start what I want is I  want to run my node mon so server dot JS alright   I will save it and now if I want to run it then  I will just do the npm start so I will hit enter   and you will see that my application is running  currently we don't have anything in our server.js   so that's why we don't see anything here now  what we are going to do is now let's create a   HTTP server so for creating an HTTP server what  we will do is I'm going to have a constant HTTP   and this will be coming from require HTTP core  module now you will see that as soon as I make   any changes my server gets restart automatically  now what we have to do is I have to have a port   where I will have my server to listen so for  that Port what I will do is I'm going to create process.env.port all right and if I'm not using  the dot EnV then in that case I want that my five   zero zero one port should be used all right  now we have the port now since we don't have   the dot EnV file let's create that so I'm gonna  go here and I will have dot EnV and inside this   dot EnV I can give the port as 5 000. all right  now you will see that uh first let's create the   server and then we will see that how we can use  this environment variable port or we can use this   port so now I will create an HTTP server so to  create an HTTP server I will create a constant   I will have the server and this will have the  http.create server and when we create a server   we get request response as param all right so now  we have created our server now what we have to do   is we need to listen the server on a port so let's  have that so I will have the server Dot listen and   this will be listening on a port we are going to  get a callback and in this callback what we can   do is we can have the console.log and I can log it  as server started on Port colon I will add my port   so this will be both and I will just close the  backtick oops I made a mistake so here I will have   the back text all right I will save it now let's  give a try and let's run this so as soon as I save   it you will see that we have the server started on  Port 5001 but now if you want to use the port from   the environment file what we can do is I will have  to use the dot ENB so I will have the dot EnV all   right we already have that package and for that  what I will do is I will have the require let's   use the dot EnV here dot config all right and I  will save it now you see that when I save it now   my server is starting on Port 5000. all right so  now we have created an HTTP server now let's throw   a simple response uh and I will say Hello World  in that response so what I will do is I will have   the response dot status I will throw in status of  200 then I will have the response dot set header   so let's have the header and in the header what I  will do is I will have the content type and this   content type will be equals to the application  Json because we are going to deal with the Json   data so if you don't know about a Json data I have  a complete tutorial on that you can click on the   card above and jump to it directly then we are  going to have the response dot right so I want to   send some data when I have it so what I will do is  I'm going to have here a Json Json dot stringify   all right and then I will pass the message here  so let's pass a message and this message will be   hello to node.js close hello the page to node.js  course all right I will save it and then what we   have to do is we are going to use the rest Dot N  so let me have the response dot end all right so   the application is crashing and that is because we  see that we have an already used Port so what we   are going to do is I'm going to delete this and  I will use the static Port which is 5001 which   I am giving all right I will save it and now we  see that we have the five zero zero one and the   server is started all right now if you want to see  the output let's go to the browser so I will go to   the browser and here what I will do is I'm going  to type the localhost 5001 so let me have the 5001   and you see that we have the message hello the  page to node.j hello the page to node.js code so   we should write proper message and what I will do  is I will simply going to change the message all   right and here I will write hello the page welcome  to node.js course all right and now if we change   this then we should be able to see it on our  browser and I will refresh it then you will see   that hello the page welcome to the node.js codes  all right so by default when we are seeing this on   the browser we are making a get request so if I go  to the inspect element and if I go to the network   Tab and if I refresh it then you will see that  we make a get request and this is a get request   to the localhost 5001 and then we see a response  as this all right but for the other methods like   the post put and delete we will not be able to  see it in the browser so for that we will need   an HTTP client and to have the HTTP client what we  are going to use is we are going to use a thunder   client in our Visual Studio code itself so you  can also use the postman but I feel that Thunder   will be more comfortable we have to do everything  inside the visual studio code itself so I already   have installed the thunder so what you can do is  you can go to the extension then in the extension   you can search for Thunder client so this is the  thunder client and you can install it and once   you install it what you can do is you will have  this thunder icon you can simply go to the Thunder   icon and you can click on the create new request  all right and in this new request what we can do   is I will just remove all this and I will have  the localhost colon 5001 then I will send this   then you will see that we get the message and  this is the message hello the page welcome to   the node.js course now let's start first building  with the get API so what I will do is I will go   to my server and now I will just remove this we  don't want that or probably what we will do is I   will just keep it as it is and I'm going to have a  switch case here so let me have a switch case for   each of the methods so what I will do is I will  have a switch and I will take the method in it so   whatever the HTTP method is and to get the HTTP  method what I can do is I can create a constant   or instead of that what I will do is I'm simply  going to take a request dot method all right now   we have the request dot method and then now we  can start creating the cases so the first case   is for the get request so whenever I have a get  request in that case I'm going to make a a more   neat and clean way of writing it so I'm going to  take out out the logic and put it into new files   and I will have a get request and in that I'm  going to pass the request and the response then we   will have the Break Tag now we can have a similar  thing for the other methods as well so let's add   them so I will have all the methods first I will  just change this to post and here I will have the   post so let me write the post this will be put I  will have the the put request so let me have the   put request and actually this will change to  post request so let me have the post request   and the last one is the delete so let me have the  delete this will change to delete request and then   we will have a default case so for the default  case I can make use of this so what I will do is   I will cut it and let's add it here and here I'm  going to change this to 404 and here I will just   make the title so let me have the title I will  just write the not found all right and for the   message we can have the route not found so let me  remove this I will have the route not found I will   save it so now if I go and want to test it then if  I go here and let's change this to options and if   I send it then you will see that we have not found  drought not found but we can make use of the put   post delete and get so now next thing what we will  do is let's implement this get request so for that   what I will do is I'm going to go to my project  and here I'm going to create a new folder and I   will have the methods here and I'm going to create  four files so first will be the get request dot   JS all right next will be the post request dot JS  then I'm going to create the delete request dot JS   and the last one will be the put request dot JS uh  now what I will do is now we have all the four and   we also need to create some dummy data so what I  will do is I'm going to go and create a new folder   I will have the data inside that and then I'm  going to create the movies dot Json I already have   some dummy data so I'm just going to paste some  dummy data here so this is I mean I have three   set of movies where I have their ID which is in  uuid then I have a title here Journal rating and I   have three records all right just for the sake of  Simplicity then what we will do is uh let's go to   the get and inside the get first I have to do the  module dot export and when I export what I will   get is I'm going to get the request and response  all right I will save it and similarly I will copy   this in all the files for post also for delete as  well I will save it and for put as well and now   what I can do is I can import all the four files  in my server.js file so if I go to the server.js   then I can here go and write constant get request  and this will be equals to the require and I will   have the methods and inside the methods I'm going  to have the get request I'm going to copy this for   the other four as other three as well this will  now change to post this will change to put and I   will change this to delete this will also change  to post this will get changed to put and then this   will give change to delete all right so I have all  this four uh methods get request post request put   and delete and I'm using them here and now I have  to write about the get request so one more thing   I want to do is uh what I will do is whenever I  uh I'm calling this get request function or post   request function and I have the request response I  have to manipulate the request here so what I will   do is uh I will have the request I will create a  new property on the request which will be movies   and then I'm going to pass the movies so now you  must be wondering what this movie is this movies   is the data that we are going to have so let's say  import that as well so I will have the let movies   because the movies was going to be changed when  we add new movies or updates so we are not going   to use a constant variable here then I'm going to  have the require and in that I will have the data   slash movie Json and now what we have to do is if  we go to the get request then in the get request   first what we will do is we are going to fetch  all the movies so to fetch all the movies what   I will do is if my request dot URL is equals to  equals to I will have the equals to I will have   the API slash movies so we have seen in our slide  that for get alt request we are going to have a   URL as API slash movies which will be our resource  then in that case I will send the response I will   set the status code so let's have the status code  and the status code will be 200. I will also have   the request dot set header and here I will set the  header as content type application slash Json all   right then we have to write the rest dot right  we need to send the data so to send the data I   will just do a Json Dot stringify and I'm going to  have the request dot movies so this is the movies   which we are fetching from the movie Json file  all right and then in the end I will have the   rest dot end so we have it but somebody's trying  to call the API with API slash some some other   resource then in that case what I will do is uh I  will have an else that if this URL doesn't match   then in this case I just want to write the rest  dot right head and that will be four not four I   will have the content type application Json so let  me add it here this will change to colon and then   I will have the address dot end and in this what I  will do is I'm simply going to add the same thing   here so if I go here and if we go here then I'm  going to add this same Json I will copy this and   let's add it here all right I will save it and  now if one we want to test it then let's go to   the Thunder client uh I will go here and then we  have the slash so if we try to access this one and   if we run it then we see that the route doesn't  found slash API if we try it we still get slash   route doesn't found but if we go to the movies and  if I send the request then we see the data so this   is the data we are fetching it from our movie Json  file all right so this is our get all movies API   now if you make change here and instead of this  you pass or you misspell something and if you try   to fetch it then we don't have such a route now  let's find uh how we can fetch an individual movie   so in that case we are going to pass an ID so if  I have movies here and if I run it then we are   going to pass this uuid in our URL so I'm going to  copy this I'm going to have it here and this will   be the request URL so first we have to get this  uuid from the request URL so first uh I will find   the base URL so what is my base URL is let's have  the base URL and the base URL will be the request   dot URL dot substring so I'm trying to find a  base URL which is this one and then I'm trying   to find the ID of the movie which we want so for  that I'm going to use a substring and I want a   substring from request dot URL dot last index so  what I am doing here is that I need a substring   which starts from here and then it should end at  here so for this what I need is I need the last   index of a slash because you will see there are  multiple slash so if I get the index of this slash   then I will be able to get a substring from 0 to  the whatever the index is plus one so that's what   I'm doing is I'm finding the last index off so the  last index of this and then I'm adding a plus one   to it all right I will save it and I can also do  a console log so that we can see what is the base   URL so this is one thing next I need the uuid so  for that what will I will do is I'm going to have   the uuid and then here I'm going to do a split so  let's have a request dot URL dot split and I want   to split with a slash then it's going to give me  an array all the URL values like I it will give   me the API movies and then this uuid so let's do  the console log of that as well so I'm going to   do a console.log and I will have the ID here now  if I go and check the terminal so let's open the   terminal and this was the terminal and what I will  do is I'm going to fire a request so when I fire   a request you will see that the URL is not found  which is correct and we see that this is the API   movies which is the base URL and the second thing  is we are doing a split of it so this give me API   movies and the uuid so this uuid I need it so what  I will do is I'm going to have the index of 3 here   all right so now I have that now what I can do  is the first I need to check the whether the uuid   which is passed by the client is a valid uuid so  for that I will create a Rejects and what I will   do is I'm going to go here I will have a constant  uh regex V4 so this is a regular expression for   uuid V4 and then I will have a new regex all right  and then I'm going to paste a regular expression   which will check for the uuid so you will easily  find it on the Internet it's nothing fancy so what   I will do is I'm going to add it here I will save  it all right we have it now the first thing what   I will do is let's remove this console log we  don't want them now okay and what we have to do   first thing that I will come here and I will have  an else if then in this else if what I will do is   I'm going to first check whether the uuid which  is passed is a valid uuid or not so for that I   will do a regex V4 DOT test and then I'm going to  pass my ID here so this is my ID so I will do and   I will add it here and this is going to return  me true or false so I want that if this is false   then in that case I need to return a response  and my response will be uh let me copy this   and I'm going to add it here all right and then in  that case my response will be 400 and I will stay   here validation failed because it's not a valid  uuid so I will have the validation failed and   then here I will write it as uuid is not valid all  right I will save it okay so we have handled this   case and now if the uuid is a valid uuid then in  that case what we will do is let's come here and   what we will do here is that uh here I will have  the else if and in this case I will just check the   base URL first because uh someone can also pass  the uuid with a different base URL so I have to   check that as well so I will have the API slash  movies or let's just first let me show why I am   adding this so what I will do is now here in this  case we have that if we do the resist DOT test   with ID and we get that it's a valid uuid then in  that case we need to return the individual movie   so for that what I will do is I will have the  response dot set header and we will just copy   this so that we don't waste time all right I have  the header I will also copy the response status so   let's have the status code and then I'm going to  copy this two as well so let's go here and I will   copy them as well now what we have to send back  we need to send back an individual movie which   a user is requesting so for that what we will  do is let's filter out the results so I'm going   to create a let filtered movie and this will be  equals to the request dot movies which contains   all the movies and then I'm going to apply a  filter on that when I apply a filter I will   get an individual movie all right and then what  I will return is I will return that if my movie   dot ID is equals to equals to ID then it's going  to return me in new array so I have that and then   what I have to do is there will be a case that  the movie which we are trying to retrieve it is   not in our file so in that case we need to return  that the movie not found so what I will do is that   if my filtered movie dot length is greater than  zero then in that case we know that we have found   the movie so for that I will have my address dot  status code so I will cut this and I will add it   here I will have my response status code I will  has the rest dot right let's write the response   and here the response will be Json Dot stringify  and I will pass the filtered movie filtered movie   all right I will just do a rest dot end and I will  save it so this is the case when we have the movie   in our database or in our file but if the movie is  not present then in that case what I will do is I   will have an else and then in that case I want to  pass I'm going to copy this I'm going to add it   and I will pass 404 because the movie not found  and here I will have the error message so let me   copy the error message from here all right I will  add the error message here and here it will be   not bound and I'm going to write movie not found  then we have rest dot end all right and now we   can remove this so we have covered almost all the  cases here now let's go and give a try so what I   will do is first we are going to fetch a movie and  I will send all right you will see that we find a   movie but someone if change this resource to test  and then they try to send the request you will see   that we still find a movie so that's where what  we can do is uh when we made the this check we   can also made an end operator and along with this  we can check the base URL so if this base URL is   equals to slash API slash movies then only we  should be able to uh entertain the request so I   will save it and now if I try this then you will  see that the route not found so I have to change   this back to movies so let me have the movies all  right I will save it and there is a case that if   a user is just manipulating this uh and one and  trying to find it then you will see that we don't   have movie with this uuid D and if we have a user  who is just trying some random gibberish and send   the request then we see that the uuid is not a  valid uuid so we made a lot of checks on this but   we built our get API and get an individual movie  so if we go back here then this is the code base   I know we are repeating a lot of things we can  write it in uh I mean we can make some common   files and use it but for now I think we can do the  refactoring later on so the next thing I want to   show you is how you can create a new movie so for  that let's go to the Post so in the post what we   will do is I can have the if request dot URL if  this is equals to slash API slash movies then in   that case I will just have a try catch block so  let's have a try and catch block and then what we   want is we need to get the data which a client is  sending to the server so to get the data what we   can do here is that first let me do a console.log  and I will have the request body and then for this   request body uh what I will do is I will have the  request dot body all right I will save it and now   if I go and see then we should be able to see the  request body so what I will do is uh let's go to   the terminal and then inside the terminal uh if  we go here and I change this to post now and let's   remove this I have to create a body so let's have  a body and inside the body what we can do is we   can take the data from here so I'm going to copy  this and I'm going to add this in my thunder all   right so this is a Json data we don't want user  to pass the ID because we are going to generate   the ID all right so we have the body and now if  I'm going to send it then we see that the body is   undefined and that is because uh whenever we have  the data stream which is sent by a client to the   server we have to make use of a something called  body passer and since we are not using Express so   we don't have the body password otherwise we will  just install the body passer and we have passed   the input request so what we are going to do is we  are going to build something similar to the parser   which is going to stream the data from the client  to the server so what I will do is I'm going to   create a new folder here all right and this new  folder will be the util folder so I'm going to   create some utilities here inside that I'm going  to create a new file I will just name it as body   parser.js and in this body password.js let's have  a module dot exports and then I'm going to have   a request here this request is the one which  is going to get us from the client so I will   have the request and let's have the arrow function  now what I will do is I will get the request then   I'm going to return a promise so let's create a  promise all right when we create a promise we get   a result and a reject method and then what what I  will do is I'm going to have a try catch block so   let's have a try catch and if there is an error  we are going to reject the promise so I'm going   to have a console.log I will lock the error and  then I'm going to reject the promise so this is   done and now what I'm going to do is I'm going to  create a body variable here and then I'm going to   create time since node.js is an event driven  I'm going to create a event to get the stream   of data so I will have the request dot on this is  going to have a data and whenever we have the call   back it's going to give us a chunk of the data  all right and then we are just going to append   that to the body variable so we're going to have  the chunk and then whenever we are finished with   the stream of data we are going to end it so  I will have the request dot on and when we are   finished in that case I will also get a call back  and then I'm going to resolve my promise with the   data which I have so I'm going to have a result  and then I will have the Json dot pass because   I'm going to get the data and the form of a string  so I will have the Json parts and I will have the   body it's very simple all right I will save it  okay so now we have this and we have also used   the module export let's import it here so what I  will do is I'm going to go here and import it so I   will have a constant request body parser and this  will be equals to the require let's have the util   slash body parcel and since we are also going to  use crypto a core module in order to generate the   uuid so I will have the crypto which is equals to  the require and I will have the crypto all right   so now we have this and now what we can do is uh  since we have created this as an async await since   it's a promise so let's have an async and then  when we use it I will just change this to a single   weight so let's add the Sync here all right when  we have the async uh first thing Let's do let's   have a body and I'm going to call the request  body passer I'm going to pass my request dot   body inside that or I will pass the request sorry  and now if we try and see then we should be able   to get the body so I'm gonna remove this and I  will add it here let's go and let's check if I run   it then you see the Promise is pending because we  haven't used the await keyword so yeah so we have   to use an update here all right I will save it and  now let's give a try I will send it then you will   see that we have the requested body now we have  to take this request body and we have to insert   it in our movie.json file so let's do that so what  I will do is whenever I get my body I first have   to create a uuid for that record so let's have a  body dot ID I'm going to create a new property and   I will have the crypto dot random oops random uuid  this is going to create an uuid for me and once I   have The UU ID what I will do is I'm going to have  the request dot movies dot push and I'm going to   change this to body uh push the body all right I  have that and then once we are done with this what   I will do is I'm going to send a response which  will be the response dot right head head and then   whenever I create a new record uh the HTTP status  code will be 201 which is a content is created I   will just have the content type application slash  Json all right and then I will just do a response   dot end all right and if there is an error what  we are going to do is uh we are just going to use   the message here so I'm going to copy this and  then I'm going to add it in my post so I will   just close this body parser and then we can add  it here and I will also want to lock the error so   let's have the console.log I will have the  error and then here let's have the response   dot right head for the error case so if there  is an error I will have a 400 I will pass the   content AS application Json so let me add it  here all right and then I will have the rest   dot end and then I need to pass my response so I  will cut this and let me add it here and here we   have the validation field and then I'm going to  write the request body is not valid alright now   I will save it and since we have an issue so  I will just remove this and I will save it and   here also we have a problem because it should not  be the part of this it should be the part of this   I will save it so uh there is an error okay I will  just remove this two lines and we should be fine I   made some mistake with the copy paste I will save  it all right so now our server is running and you   will see that if I go here and if I run this so if  I run this then you will see that we have let me   minimize this and I will just close this for now  and then you will see that we have a 201 created   and if we want to fetch it then let's go and let's  run it then you will see that we have haven't just   updated here then we have the of thought two we  have again Avengers updated but with a different   uuid so now we are able to create it as soon as I  refresh my application I will not be able to fetch   the data which I just created because I am not  updating the files so if I go here you will see   that we still have the three records so what we  have to do is I need to write the data into the   file so that I have my data persisted in the file  and we use this movie Json as a database so what   we are going to do is we need to write it into  the file so for that we can make use of a file   system so I will create a new utility file here  all right I will write it as write to file dot   JS and it's a good demonstration of using this so  what I will do is I'm going to create a constant   FS this will have a require fs and along with the  file system we will also need the path so that we   can construct the path of our movie Json file so  what I will do is I will have the constant path   require and I will have the path since we need  this uh operation to be in sync because whenever   we have a successful write in our file then only  we need to send a 201 status code to the user that   the record is created so let's have a module dot  exports and this is going to give us the data that   we want to write into the file I will get the data  and then what we will do is we are going to have   the fs dot write file sync and then we are going  to define the path so I will have the path dot   join all right I'm going to use the name which  is going to give me the directory then I need   to go one level up then we need to go to the data  directory and then we have the movies dot Json and   then the next part will be the data that we want  to write into the file so for that it will be in   a JavaScript object so I'm going to make this into  a string so let's do a Json dot stringify or the   data that we are going to have then we will have  the UTF character encoding I'm going to have this   in a try catch so that we can catch the error if  we have any problem in writing it in the file so   I'm going to cut it I'm going to add it here and  then I will have a catch so I'm going to have a   catch here I will have the error and then I  will just do a console DOT log of the error   I will save it so now we have it we have the path  of our file which we want to have and this is the   path done name uh one level up directory data then  we have movies dot Json and then we just do a Json   stringify of the data that we want to write into  the file and then we have the utf-8 okay and now   let's go here and what we will do in the post is  we are going to import it so I will go here I will   have the constant right to file and this will be  equals to the require I will have the util slash   write to file all right I will save it now what  we need to do is before sending the status code to   the client we need to write it to the file so I'm  gonna go here I will have the right to file and   I will pass the request dot movies because that  is containing my complete movie set I will save   it and in case of an error we are going to catch  the error and if we have a different route then   in that case we can just use the same which we did  in our get that the route not found so let's add   this else as well so I'm going to copy this and  let me add it here so I'm going to add it here I   will save it okay now let's go and let's try so I  have the Local Host 501 and apis I want to create   the movie I will have the Avengers and game I will  save it and then let's run it so if I run it then   we see that uh oops so we get the movies so this  is all movies I want to make a post request for   this to create a new record and I will send it  and we see that 201 the request is created and if   we go into the movies then if we refresh it then  we see that the movie is not being returned into   the file so that means there might be some issue  so what we can do is let's go to the console and   let's check so I'm going to go to the console and  here we see that we have an error and the error it   says that write file sync invalid argument type  the data argument must be of type string or an   instance of a buffer or received data all right  so what we will do is uh let's go back here and   I'm going to console log the data so I will have  a console.log and the data to write in file all   right and then here what I will do is I'm going  to pass the data all right I will save it we will   see the terminal for it so I'm gonna first remove  this and let's give a try so let's close this as   well uh I'm gonna close delete as well packet  Json as well and let's give a try so I'm gonna   run it again and here if we go and see then we  get this data and we still see the same errors   so let's go and check what we did wrong so if I go  here we have Json dot stringify of the data that   we are receiving from here and then if I remove  this I will save it and let's give a try so if   I send it again then in that case if we go to the  terminal and if we see it all right so now we did   a mistake here so if we have a path dot join then  here the path is completed all right after that   we have the Json dot stringify dot data and then  what we can do is uh we can have the utf-8 here so   we will miss so we did a mistake of a bracket now  I will save it okay so we have everything I will   just remove this and then I will have a semicolon  so now we have this and now let's give a try so   if I go back here and if I run it again then we  see that uh we are able to get the data so if I   go to the movies and if I save it then we should  be having a four records so first one second one   third one and the fourth one which is the Avengers  end game so this is what we created if we go and   see then this is what created so let's create an  another one so this time I will create an Avengers   Infinity War now I will make a request and it  says 201 create it let's go and let's get it   so if I send the request then we should be able  to see uh Avengers Infinity War so if I scroll   down then we have this Avengers Infinity War so  now we see that we have the get and the post API   the next one is I'm going to cover as the delete  one so let's go and let's see how we can delete a   record from our movies database all right so  I'm going to close this I will also close this   I will also close this I will also I just keep  this one and let's have let's close this as well   and I'm going to close this as well now let's go  to the delete and here what we have to do is in   the delete also similar to a get an individual  movie we need the ID so what I will do is I'm   going to just copy this because we are going to  have the same information here as well and then   what we have to do is uh we have to check for the  uuid so I'm going to copy this and I'm going to   have it here so if we have the regex V4 test uuid  then in that case I want to send a response as the   uuid is not a valid uuid all right but if this  is a valid uuid then in that case I will have an   else if and my base URL will be very similar to  this one I'm going to copy this and let's add it   here now if we have the base URL equal to this and  we have a Rex which is also a valid uuid then in   that case we need to delete the uh movie from our  movies.json so first I want to find the index of   the movie which I want to delete so what I will  do is I'm going to have a constant index I have   the request dot movies to get the access to the  movies so I'm going to have dot movies all right   and then I will have the find index all right I'm  going to find for a movie and then what I have to   return here is I will return if the movie ID is  matched so I will have the movie ID is equals   to movie ID I will just do a strict checking so I  will just have triple equals to so now I have the   index and once I have the index what I have to do  is uh there may be a chance that the movie which   we are trying to relate is not at all present  in our movie Json so in that case we are going   to get an index so I will have the index if this  index is equals to equals to minus 1 then in that   case I need the movie not found so let's go here  and it will be very similar that if the length is   less than 1 then less than zero then we have the  movie not found so let's copy this and let's add   it here so we have that movie not found but if we  don't have something like this then what we will   do is uh we have the movie so let's now delete  the movie from the movie.json so what we will   do is I'm going to do a request dot movies and I  will use splice so let me have the supplies and I   want to splice from the index and I have to splice  the one record from that index all right so that   will remove and then I want to write it into the  file the updated movie data so what I will do is   write to file and then this is the updated movies  after deleting the movie so I'm going to write it   and then we can just send the response back so I  will have the response head and whenever we delete   we pass a HTTP status scored as 204 and then we  will have the content type application slash Json   and then I will just have the rest Dot and Json  dot stringify I will pass the request movies so   this is not required you need to pass the Json  movies which is the remaining movies we have   after deletion of the movie so now let's go here  and let's give a try so first let's fetch all the   movies and I want to delete this Avengers updated  so I'm going to copy this all right uh probably   we have Avengers updated entry more than once so  okay so we don't have it so I will go here and I   will add it here and I will fetch it so we see  that we have this ID now we need to delete this   movie so we see that we have the movie now we need  to delete this movie I'm going to call the delete   method and then let's fire it and we see that  we have an error so there must be some mistakes   so let's go to the terminal and let's check the  error so we see that the right file is not defined   and if we go here then we see okay we don't have  it so let's import it so I'm going to have the   constant right to file this will be equals to the  require and I'm going to have it from the util so   let's go to the util and then I will have the file  all right I'll save it and let's give a try again   so now this time if I run it then we see that  204 no content and it's deleted so now if we go   and fetch that movie so if I want to fetch this I  will save it then you will see that the movie not   found because we have deleted that movie and we  will also not see that movie in our movies.json   file so if we go and we see that we don't have  that movie I mean just updated so now we have   also covered the delete uh method and now the last  one is the put if we want to update any existing   movie so let's go and let's check that so what  we need is uh first we are using a put request   that means we are going to receive the data stream  from the client to the server so for that we will   need the request body parser so what I will do is  let's remove this delete and I will go to the post   and let's get these two and I will go here let's  import this and since we also need the uuid which   we want to have an updated record so for that we  will need the base URL ID and so let's copy this   let's add it here since we are doing multiple  copy paste we can optimize this code but since   uh we can do it later on as well once we are done  with our functionality but for now let's keep it   as it is and now we need to check the uuid which  we which we have received from the client is a   valid or not so let's make a check on that so  I'm going to copy this and I'm going to add it   here so if it's not valid then in that case uh  we are going to so I have to add it here and if   it's a valid uuid then what we will do is the next  thing we will do is we are going to have an else   if we are going to use the base URL and if it the  valid uuid so I'm going to copy and add it here   now what we have to do is let's have a try catch  because we need to pass the data stream which we   are receiving from our client so I'm going to have  it let body and this will be equals to the await   request body parser I need to pass my request here  so let's have the request since I'm using a weight   I have to add an async so let's add an async to  the function so I have that and I have to add the   catch as well so let me have the catch which will  have the error block and then I'm going to Simply   write the console DOT log error and if there is an  error I will just write that the request body is   not a valid request body so I will just copy that  from here all right I will copy and I will paste   it all right so we have that case but if it's  a valid request body we get the body from the   body passer and then what we have to do is first  we need to find the index of the record that we   want to update so let's copy it from our delete  because we have that functionality built there so   this is going to give me the index then also if  the record is not present which I want to delete   I want to throw that the movie not found so I have  to copy this as well so let me copy these two oops   so it's more kind of a similar functionality we  have here so I'm going to copy and I'm going to   add that here but if we find the but if the index  is found and we need to update that record so   let's have the else here then in that case what  we will do is uh if they have the movie and we   also have the index then I will do the request  dot movies and I want to update the movie with   this index and then I will have the same uuid so  nothing is changed on the uuid but we will have   a new body which we have received from the client  and the updated one now we have updated the record   in the request dot movies which is the movies Json  now let's write the updated movie Json file so I'm   going to write the file with the updated movies  so I will have the request dot movies and then we   need to send the response to the client so what I  will do is response right head all right and then   we have a 200 in case of an successful updation  of the record then I'm going to have the content   type application Json and then response dot end  and with the response Dot and we will have the   Json dot stringify request movies and I mean  I'm sending the response back with the updated   uh movie which we have updated in the database so  for that I will use the index here all right and   if there is no case of this then in that case  we will just add the else and that else would   be this one so else let me copy this I will add  it in the delete as well and I will also add it   in the post as put as well so I'm going to add it  here as well so we have it and now we have written   all the operations so let's go and let's give a  try so what I will do is I will also close this   let's go here and here let's start with first  get all the movies so I'm going to remove and   fetch all the movies so here you will see that  we have all the movies we have total of one two   three and four records now we are going to post  it so we are going to create a new movie so let's   have a new movie and here I'm going to write as  Mission Impossible then I will just change that   it was in 2000 I will change the IMDB rating  as a 9.9 UPS 8.9 sorry and now I will send it   request all right I see that 201 the record is  created so I should be able to see the record   oops I clicked two times so that means two records  will be created so now let's go and get and I will   send it and we should be able to see two records  with the mission impossible so if I scroll we have   two records with Mission Impossible now I want  to delete it so what I will do is I'm going to   copy this less fat it first so if I send it then  we see that we have the movie now I want to delete   this so I'm going to fire a delete request and we  see that 204 no content that means it's deleted so   if I go and try to get it again I will see that  the movie is not found now what I will do is I   will just remove and I will fetch all the movies  again and now this time what I will do is I want   to update this Mission Impossible with mission  impossible one or two so what I will do is let's   say Mission Impossible Rogue Nation all right I  will make a put and I will just get the ID so this   is the ID which I want to update I will copy this  I will add the ID here and I will also change the   IMDB rating to 7.9 all right I will change this to  2015 and let's do a send I do a send then you will   see that this is the updated record which I have  received back and if I want to check that I will   just do a get request I'll send it and I get the  data back so I can also do the get all movies and   we should be able to see the updated movie which  will be the image an impossible Rogue Nation so   this way we have created the vanilla node.js crud  API project we have the get put post and delete   and we have also covered some of the responses  of different cases like the uuid is not valid we   did some validation on the data we also did some  validation on the routes we did validation on the   movie records in case we don't find a movie so  we just throw that movie not found so this was   a basic project but there's a lot of things to  learn if we are just beginner in the node.js then   there are a lot of things to run I will push the  code in the GitHub so that you can take it for the   reference and in the coming videos we are going  to explore more on the node.js and the express.js all right guys so before we jump into the visual  studio code and do some Hands-On on the Express   framework I want to quickly walk you through some  of the slides which I have prepared where we will   see what this Express framework is and what  features it offers while doing the development   of the node.js application so Express it's a  very popular node.js web application framework   and it provides a robust set of features for  building web applications in mobile applications   Express provides a thin layer of fundamental  web application and it's built on top of the   node.js features that we all know and will love  it so this makes Express a very performant now   let's discuss about some of the features which  express offers so Express is already built on   top of the node.js so it saves a lot of time  in development and that results into a faster   server-side application development next Express  also provides different middleware functions   that have access to the request and the response  object and in next function in the application for   a request response cycle let me give you a small  example of the express middleware so in this slide   we will see that we have an Express then we create  an app with the help of Express and then you have   that app.get you provide a route into it and  the other one is the middleware function so   this middleware function will have the arguments  as request the response and in next callback which   is a middleware function now once you have the  request and the response you can use the next   so that you can go on to the next function which  we want to execute so this is a simple Express   middleware function and this middleware function  also helps us to do the chaining of the routing   so you have one route which you redirect to  the another one and then you have the other   one next we want to discuss about is the routing  so routing refers how are applications endpoint   URI responds to the client request another one  is the templating engine so a template engine   enables us to use the static template files in  in our application so at runtime these template   engines replaces the variables in the template  file with actual values and transform the template   into an HTML file that we sent to the client  and the client sees it on the browser Express   uses the debug module internally so to lock the  information about the route matches middleware   functions that we use in the application mode and  the flow of the request response cycle now since   we have the basic knowledge about the features  and the express so now let's go to the visual   studio code and let's see how we can install the  Express in our node application so I'm using the   same project which we have built in our previous  node.js crash course so you will see that we have   different branches so we have the part one part  two part three and now I'm creating a new branch   which is the express get started now if we want  to install the express let's go and check the   packet Json file in the packet Json file we have  main entry of the application which is index.js   so we don't have the index x dot JS at the moment  but we are going to create that and then we have   the name version description and some test scripts  so what we are going to do is right now we don't   have anything installed as a dependency in our  node application so let's go to the terminal so   I'm going to open a new terminal and in the new  terminal if we want to install the express we can   simply use the npm install Express and this is  going to install Express in our application so   now if we want to have the express as a dependency  we are going to use this npm install Express and   if we want to install the Express in the project  temporarily but we don't want it to be added in   the dependency list then in that case we can use  the no hyphen save but for our project we need it   as a Express framework and we want to add it in  the dependency so I'm going to hit enter and this   is going to install Express in our application so  meanwhile what we can do is we can create a file   which will be the index.js so I have the index.js  and we see that R Express is also installed so   let's go to the packet Json and verify so here we  will see that we have a dependency object now and   in that we have an Express and the version of the  express all right so now our Express is installed   and now what we will do is we are going to create  a simplest Express app using a single file which   is the index.js and later we are going to see that  if we want to have a full project of the express   then we will use the X Plus generator to create  a sample project so what I will do here is that   first let's import the express so we will have the  constant Express I'm going to have the require and   then we are going to have the express all right  so we have the express and now we are going to   create an app using this Express so I will have  the constant app and that will have the express   we have created the app now we want to create our  server so I need to have a port where my server   can listen so let's add a port as I'm going to  use the port as 3001 we can also use the port   from the uh dot EnV file we can use with the help  of the process core module and for that we will   also need the dot EnV so I have covered that part  in my previous video so if you have missed then   please go and check it out I will also add the  link in the description of the video now we have   created this and now what we want we want that  our app should start and it should listen to the   port 3000 in one so what I will do is I'm going to  have the app listen and then I will have the port   and there will be a call back here so let's have  a callback and I'm going to write the console.log   and here I will have the example app listening on  Port I will have the dollar code all right and I'm   going to make this as a backpack so that I can use  the template literal okay now if we want to run   this Express app what we can do is let's go to the  packet Json file and inside the packet Json file   what I will do is I'm going to add here start all  right and then I will have the node oops index dot   JS I will save it and now if we go and write the  npm start then it is going to start my application   and you will see that the example app listening  on the port 3001. either we can go to the browser   so let me go to the browser all right and I'm  going to open it on a localhost 3001 and I will   hit enter and you will see that cannot get slash  because we haven't set any route at the moment so   what we will do is let's set our first route so  I'm gonna go to my index.js and in the index.js   what I will do is I'm going to have the app dot  get method and in this I'm going to pass my route   so if I have a slash then in that case what I  will do is I'm going to have the request and the   response all right this will be an arrow function  and whenever I have this request response what I   want to do is I want to send my response as hello  world so let's have a Hello World here all right   I will save it and I will go back to my browser  alright and now if I refresh it I still don't see   anything and that is because uh we have to restart  our server now I'm going to cancel this and if I   want to restart my server every time whenever I  make changes so I'm going to install the node one   so that it will help me for the development so  I will have the node mod I'm going to have the   hyphen hyphen save hyphen Dev because I want to  install it as a Dev dependency so now if I go to   the packet Json I should have a Dev dependency as  node mod in the packet Json I'm going to change   this and instead of this I'm going to have the  node mod all right I will save it and now let's   have the npm start oops npm start and Node 1 will  start the application now let's go and let's check   so if I go to my browser again then in that case  if I refresh it then you will see that we have the   hello world and that is because now we have added  a get HTTP method and on the route as slash so it   will send the hello world now the other thing what  we can do is now if I want to send the response   as a Json so in that case what I can do is I can  just change this I can have the Json and before   the Json I want to show you that if I go to the  thunderclion and I make a request on the localhost   3001 then we should see hello world but you will  see that this is a hello world and it's not in   adjacent format so what I can do is I will go here  we have the Json and then we can have a message   here and then we can have the hello world I will  save it all right and now if I send the request I   will get a application Json as the content format  and we see that we have the hello world and if we   try to access any other route other than the slash  then it's going to give us 404 error so we have   the four not four and we have the error so this  is the default Express error handling now the next   thing I want to show you is that uh how we can  set up some basic routes in express all right so   now we have the get route and what I will do is I  will have this and I'm going to change this to uh   this is home page all right and then now we will  set up some routes so what I will do is let's have   some sample routes as users so I'm going to have  the users and when I do uh app dot get slash users   then I need to get all the users so here I'm going  to have the message and I'm going to have here uh   get all the users and now this is the get and if  we want to get an individual user then in that   case we are going to pass an ID so I'm going to  have the slash ID and in that case I'm going to   have the get user with ID and then what I will do  is I'm going to change this to backpicks and then   I can get the ID so to get the ID what I will do  is I'm going to have the request dot param dot ID   so this is also the express feature it provides  us if we want to get the ID from the request   param now let's do the post so if I want to set  a post route what I will do is I'm going to have   the post here and it will be post to the users and  in this case I'm going to have the create new user   then if you want to use the put route so if you  want to update the user then in that case we will   have the put so all this are you have the app then  you provide the HTTP method and then you provide   the path on which the client should use the as  an endpoint and then you provide the Handler so   for the put also I will need an ID and then we are  going to have a request response I'm going to copy   this and I will add it here and now we will have  the update user with ID so let's have the update   user with ID and we will get the ID and the last  one is delete so if I want to delete a user then   we can have the delete HTTP method and then we  are going to have the ID and here we will simply   have the delete user with ID so so we have set up  some basic routes and this is how you do the basic   routing in Express so now let's go and let's check  so what I will do is I'm going to go to my thunder   client and here I will have the slash first so I  will send it and we see that this is the home page   now if I want to have the users and I'm going to  send it then you see that we get get all the users   and now if I want to get an individual user with  an id1 and let's send it then you will see that   we get a user with id1 we can simply have the put  also so if I send it you will see that we have the   update user with id1 and similarly for the delete  so if I send it then we have delete user with id1   now we will check for the post so if I remove this  and if I send it then we will see that create a   new user so this is the basic routing now the next  thing which I want to show you is how you can use   the express generator so whenever you want to  build a web application and you want to use   the express then in that case we can have a full  project of the express with template engine and   template views with the help of Express generator  so what I'm going to do is I'm going to go to the   index terminal and in the index terminal what I  will do is I'm going to change my directory I'm   going to have LS minus LTR and then what I will do  is I'm going to go to my Express tools so I will   have the CD Express 2 and let's clear it now here  what I have to do is I want to create an Express   project with the help of Express generator so I'm  assuming that you are using the node version uh   higher than 8 where we already have the npx which  is the task Runner so what I will do is I will   check my node version so let's go and let's check  the node version oops uh it should be node version   so I'm using the node as 16.13 so what I will  do is I'm going to use the npx express generator   and then I will provide the name of my app so this  will be my Express app all right I'm going to hit   enter and now this is going to scaffold all the  files and the project structure which you will see   so you will see that it created a lot of files and  a complete project for me now what we need to do   is we need to do the CD Express app so let's go  to the express app so I'm going to do LS and we   have the express app so let's go to the express  app all right so now what we will do is before   I do the npm install I want to open the express  project which we have created in my visual studio   code so what I will do is I'm going to go here I  will have a new window then I'm going to click on   open then I will just Traverse to my project so I  will have the codes Express tools and express app   and I will open it and I'm going to close all this  and I want to only show you the packet Json file   so now in the package.json file when we use the  express generator and create the express project   we already have few dependencies like cookie  passer debug Express HTTP errors Jade and Morgan   so we are going to go through the complete project  structure what we have what all files are created   and what's the use of those so now what we need to  do is we need to install the dependencies so what   I will do is I'm going to have the npm install and  this is going to install all the dependencies and   it's going to create the node modules folder with  these dependencies all right so we have the node   modules folder so that means all the dependencies  are already installed now let's go to each of the   folder one by one and understand what it is so  first one is the bin folder and inside the bin   folder we have a file with www and it is a simple  file where we create a HTTP server and with this   server we also Define the port so this is a simple  HTTP server we have and we provide the app which   we have created with the help of Express so if we  go to the app.js and in the app.js you will see   that we have the app we created the app with the  help of Express and then we just export 8 so we   have exported the app now this app is imported in  www file and then here we have the HTTP server and   we give the app as an argument then we have the  server will created the port and we'll list the   server to that particular Port so that's what it  has created now you can also create this as a part   of your app.js but since we have used the express  generator it wants to keep them as a separate so   that's why we have it www next we have the public  folder so this public folder will contain all   your static files like images JavaScript style  sheets so this is the public folder then we have   the routes so with express it creates a separate  folder for the routes so here you will see that   we have two routes files which is the index.js  and other one is the users and here you also get   the Express dot router which is help you to create  the routes so we are going to go to this later on   then we have the views so this views are actually  uh Jade templates uh it's now also known as the   Pug so now it is the templating engine and this  is how you write the Jade templates so this is   something that all the views which you see in your  browser will have the dot Jade files and here you   have the index.js in the index.js you're going to  have an H1 tag and a paragraph tag and there will   be some values with the title and these values you  can get it from the request which you created now   next is the app.js and then package.json so we  have already gone through the package.json and   let's go to the app.js now in the app.js you will  see a lot of stuff but this one the HTTP errors is   used to create the HTTP errors so it's a package  which will help you to create the HTTP errors and   the sample if you want to see is like something  like this that if I want to create a 404 error   then you can simply use the create error instance  and then you can pass the error code here so this   is what you use the HTTP errors then you have the  express which we already covered you have a path   which is a core node module then you have a cookie  parser which we are not going to use for now then   we have the Morgan which is a logger and it is  going to log all the requests which we fire then   we have the different files for the routes so we  have two files one is the index and the user and   those two are having a different routes for the  index and the users then we create an app with   an Express then we set the view engine setup so we  are having a view engine as Jade because this can   be different thing it can be handlebars it can be  mustache so depending on what view engine you are   using so we are using Jade then there is a code  which you will see like app dot use so these all   are middlewares and these some are the internal  middleware some are the custom middlewares so we   are going to cover the middle west in in our next  video so for now you don't have to worry about   what this app.use is so all these are middleware  so you you will see that we have a middleware and   as we saw in the slide we have a middleware  function which has a request response and in   next and the next will have the whatever the next  Handler you want to provide to it then we have an   error Handler middleware so this is also an error  Handler middleware where you have an error object   and then you have a request response object  with the next so now if we want to run this app   application uh how we can run it so what I will  do is debug equals to express app colon as trick   and I will have the npm start oops it should be  NVM start so you will find this uh oops I made a   mistake so it should be debug equals to so this  will be debug equals to and I will hit enter now   we see that we have the express server started  and it's listening to Port 3000. now if we go to   the browser and let's see what happens so if I'm  going to go to the browser and now instead of the   3001 I'm going to have the 3000 and you will see  that we have the express and it shows welcome to   the express so now let's see what this Express and  welcome to the express are coming from so if we   go back and in this what we will see is if we go  here then we have two routes so whenever we have   a slash index router is activated so if we go to  the index router we will have to go to the route   slash index so if we go to the routes slash index  and here you will see that when whenever a user is   requesting to a route with the Slash we are going  to get a middleware function and this middleware   function will have the request response and then  next and then whenever we have the request we send   a response and in the response we have to render  the index view so this is my index View and I'm   passing the value is title and the express and  this value will go here as title and express so   here what we can do is we can make a change so  I'm going to make a change as Express tutorial   and then I'm going to also pass a value as message  let's go to the index and we have the Welcome 2 so   I'm going to make it says welcome to express  beginner friendly tutorial I will save it all   right now we are passing the title and the message  and now if we go to the index Jade then here what   we can have we can have the title but I can make  change here and I can have the message here all   right I will save it and now we want to restart  our server since we are not using the node Bond so   what I will do is I'm going to restart my server  now let's go and let's check so I'm going to go to   my browser all right and then I'm going to refresh  and as soon as I refresh you will see that we have   the express tutorial and welcome to the express  beginner friendly tutorial so this way you can   actually send a view and instead of sending a  Json because we are not creating the API you   are actually creating a web application so you can  send different views to the client and the client   can view them on the browser all right and now we  also have the user's route so if I go and have the   slash users then we have a respond with a resource  so we can make a change here so I will go back to   the visual studio code and in the visual studio  code if we go to the users then in that case we   just have the res dot send and we send it if I  want to render a new view then what I can do is   I'm going to create a new view here and I can have  the user dot Jade and then we can just copy this   all right and then I can go to the Jade and then  I can add it here and you will notice here that we   have the extends layout and that is because this  layout because every page which is rendered on   the browser is an HTML page but you will see that  there is no HTML tags here so we have a layout and   in the layout we have specified the doctype HTML  head title link body and then we have the block   content and now we just write this block content  and in this block content we have an H1 tag and   we have a paragraph tag and here what we can do  is uh instead of the title we can make the users   all right and then here I can have the user let's  have the users all right and then we can pass the   users so if we go to the users and then here what  we can do is we can have the render and here what   we will do is uh we are going to change and we  need a view here so I'm going to save it oops I   made a mistake so I'm going to first delete this  all right and then we have the users and inside   the users I'm going to copy this and then what  we need to do is we need to send the response   dot render so I'm gonna to copy this and I'm going  to come here and I'm going to add it here and we   can just simply change this view so my view will  be a user and then we can pass the title as this   is users page and we can have the message is you  users listed I will save it and then we can go to   the user dot Jade and then we can simply have the  title so I'm going to copy this then we are going   to have the title and here I'm going to have the  message and let's go and let's quickly check so   what I will do is I'm going to go to my browser  all right and now in the browser if I refresh it   then we should be able to see but we don't see  anything but for that what we have to do is we   need to restart the server so let's restart the  server all right now we have restarted the server   so now let's go and let's check so if I go and  refresh it then we see the user pages and in this   way we can create different views for different  routes and can build a full-fledged uh web   application so we are going to build it in in one  of our video later on but for for today it's it's   just the introduction of the express generator  and the project which we get now let's go to   the visual studio code and let's understand the  project more now if we want to serve the static   files so if I go to the app.js and in the app.js  you will see that how we serve the static files   in the express application and here you will see  that we have the Express dot static and this is   a built-in middleware function in Express so we  will also see uh in in the next video that what   are middlewares and what are the different kinds  of middleware some are custom middleware some are   built-in middle valves and how we can write them  so this is an built-in middleware and here you   provide the path of your done name so this will  be the root and then from the root you will see   that you need to have a public directory and once  you have this then you will be able to serve the   static files so if I want to access the static  files like I want to access the style sheet so   what I can do is if I go to my browser and in the  browser what I will do is uh I can have the style   sheet slash style.css and you will see that we  get this style sheet now if you want to make a   change suppose let's say you want to make a change  in your virtual route then you can also do that   so if we want to do that what we will do is I'm  going to go here all right and here what I will   do is I'm going to add the slash static so let me  add the slash static and then we can pass this all   right I will save it and now if we want to access  the static files then in that case what we need   to do is we need to have the slash static because  we have added a virtual path all right and if you   want to see this then let's restart our server  so I'm going to restart our server and now we   can go to the browser and check so if I go to  the browser and if I refresh it then you will   see that we don't find any path on this allowed  now because now we have added the middleware to   access the static files but the path is we have  changed the we have added a virtual path which is   a static and now you will see that we get the  static files so this is how you can serve the   static files in Express app and now next thing  what I want to show you is that let's go to the   visual studio code and here you will see that this  is a logger and we have the logger Dev so Morgan   usually provides a different kind of parameters  here we can also have the combined or we can have   the tiny so you can read it on the documentation  of the Morgan package so I'm going to change this   to combined and before it was Dev and for that you  were seeing that you have a get static so all this   routes which you are trying to access you will see  them as a logged here so I'm going to save it and   I will change this so let's restart the server we  have the restart of the server and now if we fire   any requests so let's go to the Thunder client  I'm going to create a new request I will have this   as localhost 3000 and I'm going to have the slash  users and I'm going to hit enter then you're going   to see that we get a HTML page back and whenever  we get an HTML page back you will see that the   complete request to which we have added and it  gives more information like we are using a thunder   client and instead of thunderclient if I use a  browser then you will see that we are getting   uh different information so if I go back here and  here what I will do is I'm going to have the uses   and I hit enter and now if we go to the visual  studio code and you will see that what is the   logs we have so here you will see that the route  was accessed via apple webkit and it was a Chrome   browser and a lot more information so this is what  this uh Morgan package is so I can change back to   there all right so that's all I have in this first  video it's a basic introduction of the Express and   the express generator and I have also walked you  through the complete Express project which we get   uh with the express generator and then how we can  use the static routes basic routing and all the   basic stuff in the coming video we are going  to explore more on the routing in the Express   and also the middlewares what are different kind  of middlewares that are available in the express all right guys so let's first start with  understanding what is the middleware function   is so we will understand the definition of it  and a middleware function is a function that   have an access to the request object and the  response object and there is a next middleware   function in the applications request response  cycle let me show you a small diagram which we   have also covered in our previous video so this  is a middleware function we are just using the   express and then we are creating an app with  the express now we have created a method get   so app.get and we have a route AS Slash and then  we pass a function now this function is going to   have a request object and a response object and  there will be a next middleware function and   whenever we do some operations on the request or  the response then after that we need to call the   next and then our app is listened to a port so  this next is a middleware function which is also   a callback argument which will help us to do the  operations in request a response cycle now let's   go to visual studio code and let's understand  this practically so I'm going to go to my visual   studio code and in the visual studio code you can  see that I have a small project where I have the   index.js and the package.json dot file and if I  go to the packet Json I have no dependencies in   the project now in Express we have five different  types of middleware one will be the application   Level middleware which is used application wide  next is the third party middleware then we have   the router level middleware built-in middleware  an error handling middleware so I have misspelled   the error handling so let me correct that all  right and now we are going to write the example   of each of the middleware and the use of that so  now let's first start with the application Level   middleware so what I'm going to do is I'm going to  first import the express but before that I need to   install the express let's install the express I'm  going to have the npm install Express and this is   going to install Express in my packages file now  we have the express let's create a basic server   so I'm going to have the constant Express require  Express all right and then with this Express I'm   going to instantiate my app so I have a constant  app which will be equals to the express all right   now I have the app and let's define the port  as well so I'm going to have the constant Port   I will have the 5001 and then I will listen  to this port uh so that my application server   starts so what I will do is I will go in the end  and then I will have the app Dot listen and then   I will listen on the port which I have defined  then it will give me a callback function and I'm   going to have the console.log and then I can have  the server started on both and I'm going to pass   the port which we have so let me have the port  all right so we have created the basic Express   server now I will also need a node Bond so that  I don't have to rerun my application again and   again so I will have the npm install node mod and  I will also make change in my packet Json file so   I will go to the script and I'm going to have here  the start all right then I will Define here node   Mon and I will have the index.js all right I will  save it now if we want to run the application we   can simply use the npm start and that will start  my applications okay so I am facing an error so   let me go back to the packet Json file and we have  missed the comma here now let's give a try so I'm   going to have the npm start and we see that our  node server is started now we are going to use   the Thunder client so if I go to the ThunderClan  I will create a new request and let's clear all   my activities all right and here I can start it  so what I will do is I'm going to have the HTTP   colon slash localhost and I'm going to have the  low close 501 all right so we have the 501 and   we get 404 route not found since we haven't set  up any route that's why we are getting an error   now what we are going to do is first we to Define  an application Level middleware so what I will do   I'm going to write a small logger function so I  will go here then I'm going to have the constant   logger middleware and the job of this function  will only to lock all the requests which the   server is receiving so here what we will do is we  are going to have a request object then we will   have the response object and we are going to have  the next all right this will be an arrow function   then what we will do is we are simply going to do  a console.log and I'm going to log the request so   first let's have the date all right so I'm going  to have the new date and then what I want is I   also want the request so whatever the request  is received by the server so I'm going to have   my request and I will have the request Method All  right so this is the request method and then we   will also have the request URL so let me have the  request.url and once it is done then I can call   the next middleware function all right so now we  have created this logger middleware and now if we   want to use this so whenever we get a request we  need to lock that request and if we want to use it   through the application wide so what I will do is  here we can simply use the app instance all right   and we can make use of a use and then we can pass  the logger middleware all right I'm going to pass   it here and I will save it so if I try to make  any new request I should be able to see it so   I'm going to send it then you will see now that  this is the date and then this is the request   this is the request method and this is the URL so  if I have a API slash users and if I send it then   you will see that we have the API slash user and  get so this is a very simple a basic middleware   but this is an application Level middleware next  I want to show you is the what is the router level   middleware so what we are going to do is we are  going to create routes and for that I will have   a router from the express so I'm going to have  the constant then I will have the router all   right and this will be equals to the Express dot  router all right now we have the router and then   what we can do is we can come here and we can  create some routes so let me create first get   route so I'm going to have the router dot route  all right and then this route will have a slash   and on the slash I will have a get route and on  the same I'm going to have the post route and   here I'm going to have a function which will  be the get users and then I'm going to have a   function here which will be a create user now we  need to write these two functions so I'm going to   have the constant get users all right this will  be an arrow function and then I'm going to have   the request and the response here now similarly I  will create a another function which will be the   create users so I'm going to copy this and I'm  going to add it here and now whenever we have a   get users what I will do is I will have a simple  response in the form of a Json and then in that   what I will pass is I'm going to pass a message  and I will have the get all users so this will be   a simple get all users and then we can also have  a response for my create user so whenever someone   make a post request we are going to pass a simple  message and then it will be a create new user all   right now we have it and we can see that we have  our application is crashing so maybe we had made   some mistake but since we are using the function  before we are having the definition of it what   we will do is we are going to cut to this and  we are going to add in the end all right I will   save it and now everything works fine now what we  will do is let's do a simple test of these two uh   endpoints but before we go and test it what I  want to do is I want to add one more stuff and   that will be app dot use and then we need to add  the router here so what I will do is I'm going to   have the app.use and then I will have my endpoint  as API Resource as users and and that will contain   the router all right now we can try it so if I go  back here I have the users I'm going to send the   request and I see that get all users and if I make  a post then I will see create new user but now we   haven't done anything related to the middleware  stuff uh so what we will do is how we can define   a middleware which will act on the router level  so I'm going to create a function a simple a fake   authentication stuff so what I will do is I'm  going to create a constant and this will be a   fake auth and then I'm going to have the request  response and in next I'm going to have the arrow   function and then what I will do is I will have  a constant which will be the auth status so let   me have the auth status and I'm going to assign a  value as true and then if we have the auth status   then in that case what I will do is I'm going to  Simply have a console.log user auth status and   then I'm going to Simply print the auth status all  right and here I'm going to have the auth status   and then we can have the next so whenever someone  is trying to access my route I need to Define an   authentication on that and if the authentication  is successful then only I need to have the request   get executed and if it's not true then in that  case I need to throw an error so I'm going to have   the response status and I will Define the status  as four zero one and then let's throw the error   so I'm going to have the throw error and I'm going  to pass a message here so this will be user is not   authorized all right so now we have it and how we  can make use of this fake auth middleware function   on my routes so for that what we can do is if we  go here and here what we will do is I'm going to   have the router and then I will have the use and  then in this use I can pass my auth function so I   will have the fake auth all right I'll save it so  on every route when someone send a request then we   are going to execute first the middleware which is  the fake auth we do the authentication and if it   is successful then we will see the response  but if it is not successful in that case we   are going to see the error so right now I have  defined the fake auth as true so everything will   get successful so if I go here I'm going to send  the request and you see the user auth status is   true and we see that create new user but now if  the authentication fails so I'm going to change   this to false now let's go and try and if I send  a request you see that we get 401 unauthorized   because if the authentication fails we need to  throw an error so if we go here and there is one   thing I want to show you that you will see that  the express handles the error and it throws the   error but the response of the error is in the  form of an HTML page and this is the message   which we have passed but what we need is we need  to intercept this error response and then we need   to change this error response into a Json object  so for that what we can do is we can make use of   an error Handler middleware so this is an error  handle middleware so now we are going to intercept   the response and then we are going to change the  response into Json object and then throw it to   the user so this is the third kind of a middleware  which we are going to write so we have covered the   router level middleware now let's go and let's  write the error Handler middleware so here what   we can do is I'm going to create a constant I'm  going to have the error Handler and this error   Handler will have the error object then it's going  to have the request response and the next function   all right I'm going to have an arrow function and  I will write a constant width and status code and   then what I will do is if we have the response  dot status code then in that case we need to   pass the status code if it's not then I need to  pass a 500 which is a internal server error and   then I can simply have the response dot status  and I need to pass the status as my status code   so let's pass the status code and now we need to  handle different kinds of an error it can be a   four zero one error it can be four zero four four  zero three so what we are going to do is I'm going   to write a switch case here and in the switch case  I'm going to pass the status code So based on the   status code I'm going to pass different kind of  an errors so if it's in 401 then in that case what   I want is I want my response as Json all right  then I'm going to have the title as unauthorized   and I'm going to have the message and this message  will be whatever the error we have Dot message we   pass in the error all right I'm going to save it  and then we can just do a copy of this we can add   4404 and this will be not found all right and we  are going to have the error message and the last   one will be 500 so if we have a 500 error message  we are going to have the server error and then we   are going to have this all right so now we have  created it now the next thing what we are going to   see is uh now if I want to use this error Handler  as a middleware in my application then I can go in   the end and I can use it so I will simply use the  app dot use so this is an error Handler middleware   which is used as an application Level so I will  have the error Handler and now if we do a same   request then you will see that we still don't  see it uh let me check so we made some mistake   so I will just read it and we see the status code  before initialization so let's go back and let's   see what actually happened so we have the status  code so we did a mistake here and this should be   a response dot status code now let's go and try so  if I send the request then you see that we get an   Json response this time which is unauthorized and  users is not authorized so it should be username   authorized so I'm going to go and change this  too so now we have also seen the error handle   middleware and we have used this error handling  middleware as an application Level middleware so   we used it on the app.use and then we provided the  Handler so I made a mistake on the Handler so let   me correct the spelling I'm going to change here  so now this was the error handle middleware now we   have the get request for the Post request I want  to send some data to the server so what I will do   is first let's have a simple console.log and in  the console.log I'm going to have the request dot   body and what I will do is I'm going to add that  this is the request body received from client and   now what we will do is if we go back here in the  thunderclient I'm going to have a post request I   want to create a new user so what I will do is  I'm going to pass some Json data so I'm going   to have the name as the page oops this should be  name as the page and then what I will do is I'm   going to pass the profession as teacher and now  if I want to send this data then what we will do   is I'm going to send it but you will see that uh  okay we don't see the the response so what I will   do is let's go back here and we see that we have  a 401 unauthorized because we don't we are not   authorized to access this endpoint so what we will  do is we are going to change this auth status as   true now we will try it again and if I send the  request you see that this is the request body   received from client and we don't see any data  what we have uh provided to the server now this   is where we can use a built-in middleware in order  to get the data stream which is received from the   client to the server and then what we will do is  we can go to the inbuild middleware so what I will   do is let's cut this and I'm going to take it on  the top so that we don't mess with the other code   and here I want to use the inbuilt middleware  so I'm going to have the app dot use and then   the invent middleware for Express is we have the  Express dot Json and that will allow us to get the   data stream from the client to the server we can  also make use of an app.use use and if our request   body is in the URL encoded and we can Define  the extended as true so we have used the express   built-in middleware and now let's give a try  so if I go here and if I send the request again   this time you will see that this is the request  body received from the client and we get the data   stream which we have received from the client so  this is an example of an inbuilt middleware there   is one more inbuilt middleware which I want to  show you is the Express dot static so if we want   to serve the static files to the client then we  need to use the Express dot static so let's make   a use of it so I'm going to have the so before  using that let's go and let's do one thing so   what I will do is I'm going to create a new folder  I'm going to give the folder name as public which   will contain all the public files all right and  inside that what I will do is I'm going to create   a new folder which will be images then I'm going  to create one more oops it should not be a file it   should be older so I'm going to delete this then  I'm going to create a folder which will be images   then I'm going to create one more folder which  will be CSS all right then I'm going to create   one more folder which will be the JS and now what  I will do is I'm going to add one image in my   images folder so let me add an image all right so  I have added an image in my images folder and now   if I want to access this image from the browser  so what I will do is let's go to the browser first   and here what I will do is I'm going to have  the localhost 5001 slash API slash users and   we get that get all users so I'm going to zoom  this little bit all right but now if I want to   serve the static file which is this image then in  that case what we will do is I'm gonna go here I'm   going to have the images and then I will have the  dot PNG and you will see that we cannot get this   route so what we can do is we can make use of a  static built-in middleware so I'm going to have   the app dot use and I will have the Express dot  static all right and then I want to serve all my   static files so what I will do is I'm going to  create a path so I will have the path dot join   and I'm going to provide the static path as  public so what I will do is let's import the   path first so it's an inbuilt code module so we  don't need to install anything and I'm going to   have the path oops path and now what we will do  is uh we have the path here and then we can do   a path dot join and I will use the name and then  from the directory name I need to have the public   folder all right I'll save it and now let's go  back to the browser and let's check so if I go   back to the browser and if I refresh my page then  you will see that we have the image so I'm going   to zoom out then we have the image but if we want  to change the path so what we will do is I need   to have a virtual path which will be a static  so I'm going to have a static here and now if   I go back here and if I refresh it we don't have  such a route and what I will do is I'm going to   have the static here all right and then we have  it it so this is a built-in middleware which we   have used so now we have covered the application  Level middleware router level middleware we have   also seen the error handling middleware and the  built-in middleware the next one I want to show   you is the third party middleware so before we  go to the third party middleware we will also   add a route so if we don't Define any route then  in that case we need to throw n404 error so for   that what we will do is we can have the app dot  all so that for all other routes with asterisk   then we are going to have the request response  all right and in such cases we are going to have   the response status as 404 all right then we are  going to throw an error so I will have the error   and here I can have the route not found so now if  we try to access any of the route which we haven't   defined then in that case we are going to activate  our error Handler middleware and then we are going   to get the error in the form of a Json response so  if I go back here if I make this users and we have   the test and if I send it then you see that we  have not found and Route not found so that means   this code is now working all right now let's jump  to the third party middleware so the first one   I want to show you is the Morgan so Morgan it's  it's a library which is used for the logging so   what I will do is I'm going to install the Morgan  first all right npm install Morgan so now Morgan   is installed and let's import it so I'm going  to have the constant Morgan but Express has also   built an inbuilt middleware on top of the Morgan  so you can directly use an inbuilt middleware with   Express dot logger which is in the background is  going to use the Morgan so what we will do is I'm   going to have a logger here and then I'm going to  have the require and let's import the model and   then here we can add the logger so I will have the  app dot use and oops why I write user every time   so it will be logger and then it has different  parameters so you can have the combined Dev shot   tiny based on the parameter it's going to define  the logger so what I will do first is let's have   the there then I'm going to save it and now let's  see uh the application is still running and if I   go and if I test it then you will see that we have  the log additional logging here which is coming   from the Morgan so this one we are using from the  logger middleware which we have created and this   is one the coming from the Morgan now if we change  this to combine then it's going to give some more   information so let's have the combined and now I'm  going to send a request and this time you will see   that we have a more additional information so it's  a post API this was the route this was the HTTP   method status code this is the client which we  have used and all other information now the other   third party middleware which I want to show you  is the melter so malter is a node package which   is used to upload files to the server so what  I will do is first let's install the monitor so   I'm going to have the npm install multi all right  so this is going to install it let's import that   so I'm going to have the constant multi which is  equals to the require multi and now we are going   to build a upload functionality basically so what  I will do is I'm going to create a constant here   and I'm going to have an upload I will have  the melter and then I'm going to define the   destination of my folder where the images will get  upload so I'm going to have the best and then I'm   going to define the path so I will have my images  to be uploaded in public slash load I'll save it   now at the moment as soon as I do it you will see  that we get a folder which is the uploads folder   now I need to upload my images to the folder so  let's write an end point for that so what I'm   going to do is I will go down and here I'm going  to define the endpoint so I will have the app dot   post and then here I'm going to have the upload as  an endpoint and this is going to upload a single   image so I will have the upload dot single so that  I have only a single image and I will have the   field name as image all right and then I'm going  to have the request response in next this will be   an arrow function then I'm going to have a simple  console.log and I'm going to log the request dot   file and I will also log the request dot body  so let's have the request dot body all right and   once we upload it I need to send a response and I  will send the response the same file which we have   uploaded so I'm going to have the request dot file  and in case of an error then we are going to have   the error we are going to have the request we are  going to have the response and then we are going   to have the next so this is an error middleware  and then I'm going to have the response dot status   as 400 all right and then I'm going to send the  so this will be an arrow function all right and   then I'm am going to send the errors objects so  let me have the error and this will be an error   Dot message all right this will become the error  all right I will save it now let's try this so in   order to try this API or the endpoint the upload  I actually cannot use the thunderclion because if   I go here in if I want to upload a file there's  no option to upload a file but what we can do is   I can test it in the postman so let's go to the  browser all right and then I can have the postman   here so let me open the postman so I have the  postman and now if I want to try it what I will do   is I'm going to have a workspace as test and then  let's create a new request here so what I will do   is I'm going to go here I will have it and then  I'm going to find the Local Host colon 5001 then   I'm going to have the slash API slash users and  then I'm going to send the request then we should   be able to see that get all users but we are going  to try to upload an image so what I will do is I'm   going to remove this I will have the upload I  will just zoom in little bit oops and I will   change this to upload let's check its uploads or  upload so I will go back to my visual studio code   and then we will see the endpoint it's an upload  endpoint so let's go back all right and it's an   upload and here if I go to the body I need to send  the form data as in the form of a multi-part so   motor actually helps us to handle the multi-part  request so here what I will do is to the key uh   I'm going to change this to a file and the name  of the property will be file I'm going to select   an image so let's select an image I will go and  let's select this image and I will open it now we   have the image and now let's send it so now if we  send it then we actually see that route not found   so we made a mistake in our endpoint so let's go  back to visual studio code and individual Studio   code we have the app dot post and then we have  this so if we go back here then we see that we   have route not found because we need to make this  as post all right now if I send end it then we see   that error console loss is not a function so let's  go back to the code and here we will see that okay   we have misspelled it so I'm going to change this  to log now let's go back and now we are going to   send the request so now if I send a request you'll  see that we get a response with a field name as an   image the original name of the file is ex dot  PNG encoding mime type destination where it's   got uploaded finally path and the size of the file  and now if we go to the visual studio code then we   should be able to see it in our uploads file so if  I go here and here we see that we have the files   uh since we are not able to view those files but  the file is uploaded here and now let's go to the   index.js so this was the third party middleware  uh malter which we have used in order to handle   the multi-part request so we have covered all the  examples related to the five different types of   middleware the application Level middleware  then we covered the router level middleware   then we covered error handling middleware then  we saw some of the built-in middlewares and   in the end we saw a third party middleware so  we have used Morgan on we have used the Malta all right guys so in this video we are going  to build a contact manager application and we   are going to build the apis of how we can manage  the contacts we are also going to introduce the   authentication and authorization Concept in  order to build this application so before we   go deep dive I want to give you some overview on  the restful API conventions because we are going   to build the rest apis so this is a restful API  conventions where you will see that we have the   crud actions and first what we will do is we will  simply going to build a crude API for the contacts   and contacts will be our resource so we will have  different crud actions like get all contacts get a   single contact create contact update contact and  delete contact and for that we are going to use   the HTTP methods as get put post and delete and on  the extreme right you will see the end points so   we are having a slash API slash contacts and for  the other one we have the API contacts slash ID   so we will have to pass the ID in order to get an  individual contact or update a contact or delete   a contact and to start with this application we  need to install the node.js in our machine so I   already have the node.js installed in my machine  and if you want to install it then you can go to   the official documentation of node.js and then  you can simply install the current version or   the recommended version for the most users now  we will also need a visual studio code so you   can download the visual studio code from the  official documentation now let's jump to the   visual studio code and here what we are going to  do is first we are going to set up our project so   let's go to the terminal and I'm going to open  the terminal all right and then I'm going to go   to my documents directory so let's go to the  documents and inside the documents directory   and here I'm going to create  a new directory which will be   so this will reflect the backend apis of my  contact alright so now I will go to my contacts   directory and here first we need to initialize our  project so what I can do is I can write the npm   init and with this npm in it it's going to ask a  few questions so that it will generate our packet   Json file so for the package name I'm going to  give the name as my contacts backend API all right   version is still 1.0.0 and here it will be this  is Express project for my contacts backend API   and then the next thing is we need to define the  entry point so I'm going to define the entry point   as server.js I'm not going to add anything on the  test command I will not add the git repository no   keywords as an author I'm going to add the page  malvia and for the license I'm going to have the   MIT and then I'm going to click yes so now we have  the packet Json file now let's open this directory   in our Visual Studio code so I'm going to do an  open I'll go to the documents and I'm going going   to open the express project and inside that my  contacts so I will just click on the trust the   author and you will see that we have the package  Json now we haven't installed any dependencies and   there is not much inside our packet Json file now  the next thing what we will do is we are going to   create a git ignore file so I will go here and  I will create the git ignore and inside the get   ignore I'm going to add the node modules so we  don't want the node modules to be part of our   git repository and I also don't want to add the  dot EnV file because that will be only for the   development purpose all right so now we have that  and now let's create the server.js file so I'm   going to go here I will have the server.js so we  have the server.js and inside the server.js let's   create a basic Express server so for that first we  need to install the express so what I will do is   let's go to the terminal and inside the terminal  we will install the express.js so let's install   the npm and install Express and then I'm going  to hit enter all right so we have the express and   along with that we will also need to install the  node Bond so that it will automatically restart   our server whenever we make any changes all right  I will go to the package Json and we can verify   that we have the node mon as Dev dependency  and for the dependency we have the express.js   now in the scripts and I will add the scripts to  start my server so what I will do is I'm going   to have the start and for the start what I will  write is I'm going to write the node server dot   JS and I will also add one more which will be for  the development and for the development I'm going   to run with the help of a node mon so let's have  the node monserver.js I will save it and now if   I go and run it so let's run the npm Run Dev and  this is going to run our server.js but right now   we don't have anything in the server.js so what  I will do is I'm going to do a simply console.log   and write I am in Express project all right I will  save it and you will see that as soon as I save   this the node Bond restarts the file automatically  and we see that I am in the X Plus project so now   we have the express installed now let's create  a Express server so we'll have the express which   will be equals to the require and that will be  the express I have misspelled the require so let   me correctly and then what I have to do is I will  Define a port so I will have to define a port and   let's define the port as 5000. once we have the  express installed we are going to have equals to   the express now since we have created the app now  we can have a listen on the app on our Port 5000   so what I will do is I'm going to have the app Dot  listen and this will listen on the port that we   have created so we have the port and this port  is going to give us a callback and here we can   write the console.log and let's have the server  running on Port and we can pass the port here all   right I will save it now you see see that we have  a server running on the port 5000 so this is the   static server which we have given but usually in  our project we are going to have an environment   variable file where we are going to define the  port so let's do that so what I will do is I'm   going to create a new file with the name dot EnV  and here I will have the port and I will give the   port as 5001. I can make use of a DOT ENB package  so let's install the dot ENB package so I'm going   to go here and I will have the npm install dot EnV  so now as I have the dot e and V this is going to   give me an Access to fetch the value of the port  from the environment variable file with the help   of a process module which is a core module of  node.js so I will show you how we can do that   let's have a constant dot EnV and this will be  equals to the require and I'm going to pass the   dot EnV and then we have to use the config method  I will change this to equals to and now we have   this it has a process dot EnV and I can pass the  port and my server is now running on the port 5001   which I have specified in the environment variable  file now the next thing we need to do is since we   have created the app and we are listening on  the port now we need to test it so if we want   to test the apis we need an HTTP client there are  multiple HTTP clients which you can use but for   this project I'm going to use the Thunder client  which will be an extension inside the visual   studio code itself you can also prefer to use the  postman which will be a separate application so   you need to switch between your Visual Studio  code and the postman so that is the reason I'm   going to use the thunderclion so if you want to  use the thunderclion you can click on this icon   in the extension and then you can search for the  under client and you can just install it once you   install the Thunder client what you will see is  you will see an icon of the Thunder client so if   you can click on that and if I go and create a new  request then you will see that I'm going to remove   all this I will have the http localhost my port is  5001 and now I will just send a request so what I   will do is I'm going to click on the sender and  you will see that as soon as I click on the send   we see a 404 because we haven't configured any  route for this and we see an HTML response with   an error page now let's go and change it so what  I will do is I'm going to have the app and then   I'm going to use a get method and I want to listen  for API slash contacts so let me have the contacts   and then when I have this it's going to give me a  request and a response and this will be an arrow   function and then what I can do is I can do a res  dot send and I can give a message here which I   want so what I will write is uh get all contacts  our server is restarted and now if I go here and   for API context and now if I click on the get all  contacts now we are not passing a response as a   Json format but if we want to pass our response as  a Json what we can do is we can use a res dot Json   and this is going to give us a Json format so what  I will do is I'm going to have the message and the   message will be like this and now if I send then  you will see that we get a message in the Json   format now what we can also do is we can also  pass the status code so what I will do is I'm   going to have the res dot status and I can have  the status as 200 and then I can pass the Json   response I will save it and if I hit it you will  still see that we have the same result but what we   are going to do is we are not going to configure  all our routes in the server.js so to make a clean   implementation we are going to create a new folder  which will handle all our routes so I'm going to   go here and let's create the routes folder and  inside the routes I'm going to create a new file   which will be the contact routes dot JS and now  in the contact route.js what we are going to do is   let's first import require and I'm going to have  the express now what we need to do is now we can   configure the routes on this router so I will have  the router dot route and in this router.rout what   I can do is if I go here then we can actually  take this completely so I'm gonna cut to this   and then I'm going to add it here I will save it  and here what we can do is instead of using this   uh get what we will do is we want to make use of  a use and here we can Define our contact routes   so for that what I will do is since for every API  we are going to have this API slash contacts as a   common API URL so what I will do is I'm going to  cut this and I will have simply slash here and   here we can make use of that so we will have this  and then we need that whenever we have the app.use   so usually this app.use are known as middleware  so we are adding the middleware in our Express   project so here we will do a require and here we  can Define the path of our route so that will be   the slash route slash contact route I will save it  and then if we go in the routes now then here what   we can do is we need to export our router so for  that what we will do is let's go and let's use the   module dot export so I'm going to have the module  dot export and we are going to export the router I   will save it and you will see that as soon as we  save it now we don't see the error and if we're   going to try it in the Thunder client we will  still going to see the same results so if I send   it so we are getting an error that means we made  a mistake so here we are using the app dot use as   middleware for our API URL slash API slash context  and then we are passing our contact routes now if   we go to the contact routes we have the router dot  route and then on this route we have to Define our   get method so we are going to have a get which  is going to give us a request response and I   will save it now let's go and try so if I send it  now we see that we have the get all contacts so   this we have defined it now what we can do is uh  this is one of the route now similarly we need to   define the put post and delete so what I will do  is I'm going to copy this and since for this uh   for the Post also we are going to have the same  endpoint which will be the Slash and here we are   going to have the instead of get all contacts we  are going to write here as create contact now the   next one is the Slash and then we need to pass  the ID here so we will have the ID and then we   are going to have a put which is going to update  our contact so let's change the message as update   contact and whenever we have the ID what we need  to do is we are going to have a update contact   let's have the pair Ram so what I will do is I'm  going to use the back tick and here what I will do   is I'm going to have the request dot firearm dot  ID I will save it and for the delete I'm going   to change this to delete and for the delete also  we are going to have the ID so let's have the ID   and then here also what I will do is I'm going  to copy this let's have the backtick and then   I'm going to have here delete contact for this  particular ID we can also make a route for the   uh get an individual contact so I'm going to have  a get here I will have the request response and   here I'm going to have the get contact for this  I will save it so now we have created multiple   routes now let's give a try in our Postman first  we know that when we have a get request and then   whenever we have a get method and then we have the  contacts resource and if we send it we see get all   contacts now let's do a post I'm going to have a  post and I will send it and it says that we have a   create contact now let's have a put so what I will  do is I'm going to pass an ID which is one and I   will send it then you will see that the update  contact for one now let's go and check for the   delete it will going to give us the same delete  contact for one and if we do a get request then it   will be a get for an individual contact which will  be a get contact for one all right so now we have   all our routes and now what we are going to do  is we are going to create the controllers so that   controllers is going to contain all our Logic for  the request response and it is going to connect   with our database so what I will do is let's go  and create the controllers folder so I'm going   to go here I'm going to have the controllers and  inside the controllers what I will do is I'm going   to create my contact controller so let's create a  file and I'm going to have the contact controller   dot JS and inside the contact controller uh what  we are going to do is whenever we create the API   methods we always need to give some labels to that  so how we can give the label is I'm going to write   a description and the description will be for get  all contacts and then I'm going to have the route   so my route will be it will be a get slash API  slash contacts and then we are going to define   the access to the API so for now the access is  public later on we are going to make it as a   private whenever we when we are going to introduce  the authentication all right now I'm going to   create a constant here and that constant will be  the get contact and then what I can do is I can   simply remove this logic part from here and then  I'm going to cut it and I'm going to add it here   all right I will save it and then in the end what  I have to do is I have to do the module dot export   and I'm going to export the get contact all right  I will save it now now I can make use of the get   contact in my contact routes so let's import that  so I will have the constant then I'm going to have   the get contact and this contact will be coming  from the so I will have the require dot slash dot   dot slash controller slash contact controller and  now what I can do is I can make use of this get   contact and I can add the get contact here I will  copy and then I will add it here now this way we   can also uh modify for the Post get put in delete  so let's go and create it so what I will do is I'm   going to copy this for the create so in this it's  going to be create contacts so let me change this   to create contact and this will be changed to  create new contact so let's have a create new   contact all right I will change this to contact  this will now change to post and the access will   still be the public and then whenever we create a  new contact we actually going to give a response   as 201 which is as resource created now this will  get changed so let's go and get it from here so   I'm going to go and take this out I'm going to cut  it and let's add in my create contact I'm going to   change this to zero one I'll save it now we need  to expose this so let's have it here now let's go   and create for the put for delete and I'm going  to add it for get an individual contact so this   will be the get contact this will become a get  request here we need to pass an ID all right this   will be a public and here we are going to have a  get contact all right and then we can just add it   from here so I'm going to cut this and I'm going  to add it here so let me add it here and since we   are getting an error because this should be get  contacts and this is the create contact which we   are going to change it here anyway all right so  we have the get individual contact and the next   thing is let's update the contact so let's have  the update contact this will be changed to update   contacts so I'm going to change it to update  contact and then we can change this so let's   go to the routes and from the routes I'm going to  copy this cut and then add it here and the last   one is the delete contact so let's have the delete  contact this will now change to delete this will   change to put this will change to delete and then  we have the delete contact API slash contacts and   this will have the ID we forgot to add ID here  so let's add the ID as well the access will be   public and then we are going to add remove it from  here cut it and let's add it here all right so now   we have created all the methods in our controller  now we need to expose them so I will going to have   the get contact then I'm going to have the update  contact and then there is a delete contact now we   can use all these method in our routes file so I'm  going to copy this and let's add it here now we   have it now let's add the method in our route so I  have a create contact so I'm going to copy and I'm   going to add it here for get contact I'm going to  add it here and this will become get contacts so   this will get changed to get contacts so we have  to go and change here as well this will be the get   contacts I will save it now let's go here I will  save it here as well and then we have the update   contact so let's add the update contact and then  the delete contact so I'm going to add the delete   contact as well so we have defined the routes we  now also have the controller which is going to   contain the logic of all our request connection  to the database now what we can do is here we   can actually simplify mode and what we will do  is since you will notice that these two routes   are almost the same so what we can do is we can  actually write here dot post and cut it and I'm   going to add it here now we can remove this so  this way it can help us to save some lines so for   the other three routes we have a common uh route  so we are going to just cut and we are going to   add it here so let's add it here and I'm going to  remove this now we have it and now let's give a   try we are going to test our apis again so if I go  here and if I have the contacts then we still see   the contacts so our apis are still working we have  the foot I'm going to add the ID I still see the   ID for delete I still see the ID and for the get  individual contact I still see that so everything   works fine so the next thing we are going to  do is we are going to accept the body from   the request so what we will do is if we go to the  thunderclient and if we we do a post request and   inside the post if we want to pass a body so let's  have a body so what I will do is for the contact   I'm going to have the name so let's add the name  as the page I'm going to have my email address so   let's have the the page at the rate gmail.com and  then I'm going to pass the phone number so let's   have the phone and I'm going to add some random  phone number now I'm going to send this request   so that we can create the new contact so if we go  in our contact controller then we will see that   let's do first the console log of the request so  I'm going to have the console.log I will have the   request dot body so I need this body in order  to create the new contact so I'm going to have   the console log so the request body is and I'm  going to have the request body now if I see in the   terminal and if I go here and if I click on the  send then you will see that the request body is   undefined and that is because whenever you need to  accept some data from the client to our server we   need to use a body passer so that we can parse the  stream of the data that we are receiving from the   client and for that what we have to do is we need  to make use of a middleware and express provide us   the middleware for the Json object which we can  get it from the client so what I will do is I'm   going to go to my server.js and in the server.js  we are going to apply a inbuilt middleware which   is the app dot use and then here I can have the  express and I can have the Json and now this is   going to provide a passer which will help us to  pass the data stream that we receive from the   client on the server side so if we go back and now  this time if we send a request then you will see   that we get the body which is the name email and  the phone number which is the contact that we want   to create now what we will do is now if case if  we don't pass any body so if we don't have any of   the body and if we still send it then we are going  to see the empty body but we don't want to accept   this so now let's see how we can do the error  handling with the help of the X Plus framework so   if we go to our controller and in the controller  what I will do is now we have the request body uh   first I'm going to destructure it so I'm going to  have the name email and the phone and this will be   coming from the request dot party now I'm going to  apply a condition that if we don't have a name or   we don't have an email or if we don't have a phone  so in that case what I want is I want to throw an   error so I'm going to have the response dot status  the status will be 400 and then I'm going to use   the throw keyword and then throw an error and here  I'm going to write is as all fills are mandatory   all right I will save it and now let's see so if I  go back here and if I send a request then you will   see that we get an error we also see that we have  an error message all fills are mandatory but you   see that this error message is not in adjacent  format it's in the form of an HTML so for that   if we want to change it what we need to do is we  need to create a custom middleware which is going   to accept the request response and then in between  it's going to transform the response into a Json so what I will do is I'm going to create a new  folder and I will name it as middleware and inside   the Middle where I'm going to create a file with  errorhandler.js so I'm going to go here let's have   the error handler.js I will just make it camel  case and now in the error handle.js what I can   do is I'm going to create a constant error Handler  and this is going to have a request response next   and then the first parameter will be an error  all right so we have that and this is going to   be an arrow function and then what we can do is  we can simply do the module dot export so let's   have the module dot export and we can export the  error Handler and now if we want to use this error   Handler we need to apply this in our server.js so  if we go to the server.js then what we can do is   we can make use of the app dot use so whenever  we need to use a middleware we make use of this   app dot use and we need to use the error Handler  now the error Handler is auto imported so now we   have created an error handle middleware and we  have also used it in our server.js now let's   transform this so what I'm going to do here is  that I'm going to create a constant I will have   the status code and this status code will be in  the response so if we go in our controller then   we see that we have passed the status as 400 so  if we have a status code we are going to pass   that status code but in case if we don't have it  we are going to pass a status code of 500. all   right I will save it and then what we can do is we  can create the response dot Json we are going to   intercept it and then in the response.json I can  have the message and then I will have the error   Dot message and along with this I can also pass  the stack Trace so let's have the stack Trace I   will change this to Capital and then I can have  the error dot stack so this we get it on the error   object and now if we go and try it then let's go  to our okay I will close this I will close this   as well I will close the environment file as well  and now if we go and try and I will send it so in   this case you will see that we get a error message  in the form of a Json so we have the message all   fills are mandatory and this is the stack Trace  so now you can make a condition that you need to   display the stack trace on the dev environment and  or on the development environment and then on the   production you don't want it so you can make this  condition as well so now we are we are going to   use the stack Trace so you will see that it will  also show us that in which file it has a problem   and it will show all the stress of our files now  what I'm going to do is that if we go in our error   Handler then in this case I need to pass some more  information so I will also need to pass the title   because I'm going to have the different kind of an  error messages it may be 400 it may be 401 for 403   so so we need to handle each of the errors so what  I will do is I'm going to have a title and in the   title I will say that it's not found so I will  have the not found all right I will save it and   now what I will do is in case of a validation  error we are going to pass the 400 so for   that what I will do is uh I'm going to have here  validation fail and then we are going to have the   error message whatever error message we pass in  our error object and then we have distractors so   what I will do is I'm going to write a switch case  here so let me have a switch statement and then   in the key I will pass the status code so let's  have the status code and now here if the status   code is 400 then in that case what I need to pass  is I need to pass that it's a validation field so   I'm going to cut this and I'm going to add it all  right I will save it and now if the status code is   404 not found then I'm going to have the case as  404 and then I'm going to pass this as my response   so I'm going to cut it and I'm going to pass it  here so what I will do is I'm going to create a   constant file so that I can handle all my error  codes so I'm going to create a new file and I'm   going to have the constants dot JS and here what I  will do is I'm going to have the exports.constant   and this will be an object and here I will have  my constants so I will have the not found which   will be four not four then I'm going to have the  validation error and that will be 400 then I'm   going to have the unauthorized that will be four  zero one then I'm going to have the Forbidden   that will be four zeros3 and then we are going  to have the not found so I have different HTTP   error methods for the client and now I can make  use of this in our error Handler so what I will   do is I'm going to import the constants first so  let's go here and I'm going to have the constant   and this constants will be coming from let's have  the require and then I'm going to have the DOT dot   slash constants and here instead of 400 what  I will do is I'm going to have the constants   dot validation error here I'm going to change this  to constants dot not found I'm going to copy this   and I'm going to add the unauthorized as well  as the Forbidden so here I'm going to have the   unauthorized here I'm going to have the Forbidden  and I'm also going to add the error 500 which is   the server error so this will be the server error  and this will be 500 all right I'll go back here   and for the unauthorized what we are going to add  is we are going to add the title as unauthorized   so let's change this to unauthorized and then  forbidden this will be forbidden and then let's   add the last one which is the server error and now  this is going to be the server error so let's have   the server error and I'm going to change this  to server error and in the default case I'm   simply going to have a console.log so let's have  a console log and I'm going to write here no error   all good all right so now we have created our  error handle middleware and now we can throw the   error in our controller whenever it is required  all right so now the next thing we need to do is   now since we are going to use the mongodb and the  Mongoose so whenever we interact with the mongodb   we always get a promise so in order to resolve  that promise what we will do is we are going   to make use of an async await so let's have the  async here I'm going to add the async on all the   functions all right we have it async but now since  whenever we use the async and if we want to catch   an error we need to make use of a try catch block  and in order to do the try catch block we have to   add the try catch Block in each of the functions  but there isn't better way to do this and that's   where we can make use of a middleware which is an  Express a sync Handler which is going to handle   our exceptions inside the async express routes  and then it it's going to pass them to the express   error Handler which we have created here so for  that let's install the express async Handler so   what I will do is I'm going to go here and here  I'm going to do an npm install Express async   Handler and this is going to install our Express  async Handler now let's import that so what I   will do is I'm going to have a constant I will  have the async Handler so let's have the async   Handler and this will be equals to the require and  it will be coming from the express async Handler   and now in order to use the async Handler what we  have to do is we need to wrap this complete async   into this async handle function so I'm going to  have the async Handler and then I'm going to wrap   this all right I will save it now we don't have to  write all the try catch blocks in order to catch   the errors so async Handler will automatically  whenever an exception is occurred it's going   to pass it to the error Handler now what I will do  is I'm going to add add it in all the functions so   let's add it here I'm going to add it here let's  add it here and we can do similar on the other all   right this is for the put and the last one is the  delete so let's add for the delete all right so   now we have added the async Handler on all the  functions in our controller the next thing we   need to do is we need to have the mongodb database  setup so now let's do the mongodb setup and I will   go to the browser all right and here we can type  the mongodb so let's have the [ __ ] DB so this   is the home page of the mongodb and then we need  to create a account which is a free so I'm going   to click on the sign in you can use your Google  account or GitHub account or you can have your   email address so I'm going to click on the Google  and I'm going to use my Google account all right   so this is going to take a while to sign in using  the Google account all right I'm going to click   on the accept and I'm going to click on submit all  right now you can fill this information like what   is your goal so I'm going to Simply have the learn  mongodb or I can build a new application or let's   have the Explorer what I can build then what type  of application you are building we are building   some application related to let's have a the other  and then we are going to build a my contacts all   right and then what is the preferred language we  are going to make use of a JavaScript then we are   going to click on finish and then we can choose  the free plan which is a shared so I'm going to   click on create here and then here you can choose  any of the cloud provider region so let's keep it   as it is I'm going to choose the AWS I'm going  to have the region as let's change the reason to   Frankfurt all right and then I'm going to have the  cluster so we are going to keep as it is we are   not going to change anything and it's free forever  then we are going to have the additional settings   we don't have to do anything here and in the  cluster name we can give the cluster so I'm going   going to give the cluster as the page cluster all  right I'm going to click on create cluster so now   we have this uh now for the security quick start  we are not going to make any use of a certificate   in order to connect to our database so we are  going to use the user name and the password so   for the username and the password I'm going  to provide admin admin make sure you provide   the secured password so I'm going to click on the  create user since my user is created and then what   I will do is where would you like to connect from  I would like to connect from my local environment   and then here you can click on the add my current  IP address that is going to whitelist your IP   address to access the database and then you can  click on finish and close so now you will see that   we have the database deployments and it's going  it's creating our cluster so it's going to take   some time to create our cluster so let's wait for  it so now you see that our cluster is ready and if   we go and do the browse collections then right  now we will not have any any collection in our   cluster so collections is kind of you can think  as a database and inside the collections you can   store the records in the form of a Json object now  what I will do is I'm going to click on the add my   own data and for the database I'm going to have  the my contacts backend and for the collection we   are going to have the collection of our contacts  so let's have the contacts I'm going to click on   the create and now you will see that we have the  collection as contacts all right so now we have   created database and we also have the contacts  collection now if you want to connect our database   what we can do is we can go to this and we have a  different solutions here so we can use the compass   shell or vs code plugin so I have a vs code plugin  so if I click on it and then we can download the   vs cloud plugin from here and then once you have  it we can open it in your Visual Studio code so   if I want to connect it what I will do is let's  go to the overview and I will go to the connect   and then here what I will do is uh we can click  on the mongodb compass and here I can copy this   all right I will copy this and now let's go to  the visual studio code in the visual studio code   if you have the plugin then you have this icon  and then you can click on the add Connection in   the add connection you connect with a connection  string so I'm going to click here and then we can   add the connection string here since our database  name is my contacts backend and we have to change   the password as well so I will change the password  as admin and I will hit enter now you will see   that the connected to the cluster we have it  and now if I expand this then you will see that   we have a database which is a my context and we  have the context So currently we don't have any   documents in our context so we don't see it here  so whenever we add the contacts in our database   we are going to see it in our mongodb plugin as  well so now we need to connect our application to   the mongodb database so now let's go back to our  browser and here what we will do is I'm going to   click on the connect and this time I'm going to  connect with the mongodb native driver so this is   what we are going to use so I'm going to copy this  and then I will go to the visual studio code let's   go to the application and then here what we will  do is I'm going to close all this error hander I'm   going to close the contacts and here I'm going to  create the environment variable and let's add it   here so I'm going to add this here now I'm going  to name it as the connection string so let me have   the connection string and my connection string  is this one I'm going to change this to admin   and then here I'm going to add my database name so  my database name was my contacts hyphen backend so   oops I made a mistake so this will be before the  question I will save it so now what we are going   to do is let's create a new folder and I'm going  to name it as the config so I'll come here I'm   going to create the new folder I will change this  to config so let's have the config effect and now   in order to connect with our mongodb database  we will need a mongoose which is a object model   design schema for our entities like contacts or  user and it's help us to communicate with the   mongodb database so for that what I will do is I'm  going to create a new file and I will name it as   DB connection dot JS now let's go and install  Mongoose so I'm going to have the npm install   Mongoose so this is going to install Mongoose to  our application we can verify it with the packet   Json and we see that we have the Mongoose here  I'm going to import the Mongoose so let me have   the Mongoose this will be equals to the require I  will have the Mongoose here and then what I will   do is I'm going to create a function which will be  the connect DB I'm going to have an arrow function   and then inside that what I will do is and this  is going to be an async function so let's add a   async and then I'm going to have a try and then  then let's have a catch block that will catch the   error and if there is an error we will log the  error so let's log the error and then if there   is an error I just want to exit so I will have the  process exit and I'm going to pass one I will also   export this connection DB so what will I will do  is I'm going to have the module dot exports and   this will be equals to the connection DB and what  we are going to do in a try block is we are going   to create a constant connect and that will be an  await uh oops a weight we will have the Mongoose   dot uh we have a method which is a connect and  then we are going to pass our connection string   so that will be the process dot EnV dot connection  string so I'm going to copy this connection string   and I will add the connection string here I will  save it and then when we have this connection   established let's have a console log so that  we know that the connection to the database is   established so I'm going to have the database  connected and then and I'm going to add some   parameters here so which will be the connect  dot connection dot host so if we are going to   console log disconnect then you will see that you  have some properties on this connect and then you   can add those here so I'm going to have this and  I will also have the database name so I will have   the comma and then I'm going to change this to  name I'll save it and now you will see that if   I save it then we don't see anything because we  haven't used the connect DB uh function at the   moment so let's go to our server so I'm going  to go to my server and inside the server what   I will do is I'm going to call this connect DB so  this is my connect DB and I'm going to call it I   will save it and now you will see that as soon  as I save it or you will see here that we have   in the console log database connected and this  is the database that we are connecting and this   is the host actually that we are connecting and  this is my database name so we have successfully   established the connection and the next thing we  are going to do is we are going to create the the   schema for our contacts so now let's create the  schema model for our contacts so what I will do   is I'm going to create a new folder and I'm going  to name it as models and inside the models I will   create a contact model so let's go here and  create a new file and I'm going to have the   contact model dot JS now we have the contact model  now let's import the Mongoose so we are going to   have the Mongoose require oops require Mongols  and then we are going to create a constant and we   will have the contact schema so this schema will  actually have all the values that we want in our   contact resource so I will have the contact this  will have the Mongoose dot schema now we have an   object inside that and inside that object what we  will do is we are going to have the fields that we   want in our contact object so first thing will be  the name all right and the type will be a string   so let's have a height and I will change this to  string then I will also have a required so let's   have the required because we need this and then we  will change the flag as true and we will also pass   in case of an error please add the contact name  all right I will save it now the other field we   want is the email address so let's have the email  address and I'm just going to do a copy paste and   I'm going to have the contact email address and  the other field will be the phone number so let's   have the phone here and then it will also be a  string please add the contact phone number so I'm   going to change this to phone number I will save  it and then we can also have the timestamp so what   I will do is I'm going to add the timestamp here  I will have the time tabs and then I will have it   true and now what we need to do is we just need  to do an export so I will have the modules dot   export we're going to have the Mongoose dot model  and then we can provide the name to this model so   let's have the name as contact and we can have  the contact schema so I'm going to copy and I'm   going to add it all right I will save it okay  so now we have created the Mongoose object so   now the next thing we will do is we are going to  apply our current operations and let's let's store   the data in the real database so I'm going to go  to my contacts so now let's start with the get   contacts so first we have to import the model so  I will have the contact and this will be equals to   the require I will have the codes dot dot slash I  will have the models and inside the models we will   have the contact model now we have the contact  model and now what we will do is I'm going to   have the constant contacts and this contacts will  be equals to the contact model Dot and it exposes   some methods to us so that we can establish a  communication with the database so what I will   do is I'm going to have the find and then after  that what we can do is we can copy this context   and then we can pass this contacts as the Json now  let's give a try so I'm going to close this and   let's close this as well uh we don't want uh this  as well and if we go back here if I go to the get   and if I send a request so we see that the request  is still processing so let's cancel this and let's   go back and we see that we have the contacts and  we are using the async but we haven't used the   await here so let's use the update now let's go  back and let's give a try and then you will see   that we have an empty array so right now we don't  have any contacts in our database so now let's go   and create a new contact so what I will do is here  we have the async Handler we have the request body   is a request dot body or we are going to go here  and let's have a post and let's add the body here   so I'm going to have the name as the page let's  have the email address so the email address will   be in the page at the rate gmail.com and then  let's add the phone so let me add the phone and   the phone will be let's add some random and now  if we go back to our controller then in the case   if we want to create a new contact so we will see  that first we will have a check if the name email   and the phone is empty then we throw an error but  if they are not empty then what I will do is I'm   going to create a contact object then I'm going  to create but if they are not empty then I'm going   to create a constant with a contact and then I'm  going to create a contact so let's have the update   and then I'm going to have the contact model dot  create and then I'm going to pass the object in   the object I'm going to pass the name and this  name will be equals to the request dot body dot   name but I have already restructured it and since  in the es6 if the key and the value are same we   can just use the key then we are going to have the  email and then we are going to have the phone I   will save it and then once it is created then in  that case what we can do is we can throw we can   have the response dot status 201 Json and then we  are going to pass the contact that we have created   so let's pass the contact I will save it now let's  go to the new request and now let's fire a request   I will send it and then you will see that we have  created a new contact name is the page email phone   number we have the ID which is auto generated  from the mongodb and then we have the created   ad and the updated at the timestamps now if we go  here and if we want to check then we see that we   have the contacts and in the context you see that  we have a record and this is the record that is   stored in our collection now let's go back to our  code I will close this let's minimize this and now   let's work on the get contact so if we want to  get an individual contact then we can just use   the find by ID so let's go here and what I will do  is I'm going to have a constant contact and this   will be equals to the await let's have the contact  model dot find by ID and we can pass the ID with   the request dot param dot ID if we don't find any  of the contact then we are going to throw an error   that a contact is not found so what I will do is  I'm going to have if we have the contact then in   that case what we want is we want the response dot  status would be four not four not found and then   we will have to throw an error so let's throw an  error with new error and then we are going to have   the contact not found but if we find the contact  then we are going to return the contact so let me   have the contact I will save it all right so now  let's go and let's give a try so if I go back here   I will fetch all the contacts and then I want to  get this individual contact so I will get the ID   I'm going to copy this and I'm going to pass the  ID here and then I'm going to send the request now   you will see that I get an individual object with  the ID now let's make a change here I'm going to   change it to 9 and then I'm going to send it so in  this case you will see that not found contact not   found we don't have any contact associated with  this ID so now let's do the next one which is the   update contact so in order to update the contact  first we need to fetch a contact so I'm going to   copy this as it is and then if we find the contact  then I'm going to have the updated contact so I'm   going to have the constant updated contact and  this updated contact will be having a a weight so   I can have the contact model dot then I will have  the find by ID and update and inside this what I   have to pass is I want to pass the ID which I want  to update so I will have the request.param dot i   ID the next will be the new body which I want to  update which is the request dot body and then I   also need to pass the and then I need to pass  a query option uh which will be the new and I'm   going to have it as true I will save it and then  once we get it then what we are going to do is   uh we are going to have a response dot status and  then we can actually pass the updated contact to   the user so I'm going to have the updated contact  all right I will just copy this so now we have the   updated contact let's go and let's give a try so  this was my contact so if I click I will get the   contact sorry the contact is not found so I will  change back the ID which was eight and we have the   contact now I want to update this contact with the  new information so I will have the page malvia and   I will also have my email as the page.malvia oops  so the page dot file via I will make a put request   and let's click on send and you will see that as  soon as I send it the record is updated with the   page malvia and now let's go and let's get the  record so we will get the new updated record and   the last one is we need to do is the delete in  our current operation so let's go and let's do   a delete so for delete also first we need to fetch  the contact which is available in the database so   let's go and let's copy that all right we have the  contact if we don't find the contact we throw that   contact not found and if the contact is available  then in that case we will just do a remote so what   I will do is I'm going to have the await contact  dot remove so we have the remote all right I will   remove the contact and then I will just pass the  contact which we have removed so I'm gonna go and   change this to here I will save it now let's  go and let's try so I'm going to click we get   the contact now I'm gonna delete this contact so  let's go and let's delete it I'm going to click   on delete and you will see that it's 200 okay that  means the contact is deleted and now if I try to   to this contact then I should not be able to get  it I will should get that contact not found and   you will see that we have the contact not found  so now we have done the crud operations we have   done the read write delete and update and we  have also done the connection with the database   and all the contacts are stored in the data page  in the form of documents under the collections   so now the next thing what we have to do is  now we need to introduce the Authentication so now let's start with the authentication uh  module and in the authentication what we will do   is we are going to provide some endpoints which  will help us a user to register themselves and   then log in and once they log in they can use a  access token and then with the help of the access   token they can manage their contacts so now let's  start with the routing first so what I will do is   I'm going to go to my server.js and inside the  server.js I'm going to copy this and then I'm   going to add here and this time our API URL will  be the users as we are going to register the user   and then we are going to have a login user so what  I'm going to do is I'm going to change this to the   user routes so let's have the user routes and  now let's go and create the user routes file so   I will go to my routes and inside the routes I'm  going to create a new file which will be the user   routes dot JS so now in the user route.js let's  first import the express so I'm going to have   the constant I will have the Express and this  will be equals to the require and I will have   the express and then I'm going to have the router  so let's have the router and this router will be   coming from the Express dot router method so I'm  going to call the router method now let's create   the route so what I will have is I'm going to  have the router dot post and on this post I will   have the register and when we have the resistor  we are going to have the request response and   then we can have the response dot Json and this  responsecon B I will have the message and I will   have the register the user and then we can have  a login endpoint so that will help our users to   log in so I'm going to have the login and I will  also create one more endpoint that will give the   information of the current user so let's have a  slash current all right I'm going to change this   to login user so let me have the login you user  and I will change this to current user information   so let's have the current user information and now  let's give a try so I will go back here and here   instead of this I'm going to have the users slash  register and I'm going to send so I see that we   get an error so it should be a post request so  now let's send it and we still see an error so   probably let's see that our application is running  or not so I'm going to open the terminal and here   what we see is that we have an error and the error  is Express dot router is not a function all right   so we made a mistake now let's go to the user  route and this should be capital r now I will   save it and we still have an error now let's go  and fix that in the server.js on line number 13   we have an error so I will go to the server.js and  online number 13 we have an error that there is no   user route so we need to export the user route so  let's go here and let's have the module dot export   and I'm going to export the router all right  so that it is now available in my server.js now   everything works fine let's go and let's check so  if I go to this URL or API uses register and if I   make a send then we see that we have registered  the user similarly let's go and check for the   login and I see that we have the login and then  let's have the current user so if I click then we   see the current user but since the current user  should be a get request and not post so let's   go and let's make this change so it should be a  get request all right so now the next thing we   will do is we are going to create the controller  for the users so let's go to the controller and   let's create the usercontroller.js so I will go  here I will have the user controller dot JS and   then in the user controller.js what we can do is  we can just do simply a copy paste of this and   I'm going to have hit here and the first thing we  are going to have is to register a user so let's   have a register a user and we are going to have a  post method this will be users slash register and   this will be a public access so anyone can access  the endpoint and then register the user we will   change this to register user whoops so this will  become registered user and inside this this one   we can now remove this and we can go to the user  route and we can cut this and we can add that in   the controller so let's go here and let's add in  the controller I will save it and now let's go   and Export it so I will have the module dot export  and then we will export the registered user so I'm   going to copy and I'm going to add it here now we  will also need to import it in the user routes so   we can import it so let's have the register user  and you will see that it gets Auto imported so   now we have to create the login user as well so  let's go to our controller back and I'm going to   copy this I will add it here and I will change  this to login user so this will be login user I   will have the login user this will be a post API  and the endpoint will be the login it will also   be a public endpoint and then we can change this  so let's go here and I'm going to cut this and   let's add that in our controller so I'm going to  go here and I'm going to add it here and I'm going   to export the login user as well now the third one  is the current info of the user so what we will do   is let's create one more method all right and this  time this method will be a private method so only   a logged in user can get the current information  of a user so now this will change to the current   user info the endpoint will now change to current  it will be a private and here I'm going to have   the current user let's cut this so I'm going to  cut this and I will add it here so let me add that   here and I will save it we are going to to now  export the current user so let's add the current   user and let's import the current user here so I'm  going to import the current user and I will also   import the login user now let's copy the login  user and provide the login user function here   and for the current user I'm going to provide the  current user here I will save it and we see that   we get an error so let's go and see what the error  is so in the user controller line number four so   let's go to the user controller and on the line  number four uh we see that I don't see any error   but what is the error it says a sync Handler  is not defined and we need to import the async   Handler so what we will do is I'm going to have  the constant async Handler and this will be equals   to the require and I will have the express async  Handler all right I will save it so now everything   should work fine we see that now we don't see the  error and what I will do is I'm going to close   this contact controller and also close the contact  model and now let's give a try so if I run it then   we'll still see that we get the correct response  register the user so now we have created it now   the next thing what we have to do is uh we need to  make the functionality for register the user and   for that first we have to create the user model so  let's go and create the user model so I'm going to   go here and I'm going to create a new file and  let's name it as the user model dot JS and in   the usermodel.js let's import the Mongoose this  will be equals to the require and I'm going to   add the Mongoose here then I'm going to create a  constant with user schema and this will be equals   to the Mongoose dot schema and this will be an  object and what values we will need in order   to register a user the first property I need is  the username so let's have the username and this   username will be of type ring so I will have the  username of type string then I will have the I   misspelled it type then I will have the required  and yes the spill is required so I'm going to have   it as true and I will have a message as please  add the user name the second field is uh we need   to have an email address of the user to register  the user so for that I will have a type as string   and then I will have the required field so let me  have the required and the required will have the   flag as true and then the message is please add  the user email address I'm also going to add one   more property which is the unique so that I need  a unique email address every time when a user is   registered so no duplicate user with the same  email ID can register themselves so I will add   a property called unique I will have the flag as  true and then whenever someone tried to register   themselves with the same email address what I  will have a message that email address already   taken so that we can prevent them to register  twice with the same email address and we will   also need the password so let's have the password  fill I will have the type as string all right then   I will have the required fill so let's have  the required and it will have a flag as true   and I will have the please add the user password  all right I will save it and I will just change   this to small L and then we will also need the  timestamp so let's add the timestamp so I'm going   to have the timestamps and I will have it as  true and then what we can do is now we can use   the module export and we can export the schema  so I will have the module exports and this will   be equals to the Mongoose dot model and let's name  the model as user so I will have the user and then   I can have the user schema so now we have created  the model as well the next thing what we can do   is now let's write the functionality in order to  register a user so I will go to my controller and   whenever a user wants to register themselves they  need to provide the username email address and the   password in the request body so what we are going  to do is uh let's destructure those information so   what I will do I will have a constant I will  have the username the email address and the   password of the user and all these three fills we  will get it from the request dot body and once we   have it we are going to make a check that if the  username is not empty or the email is not empty or   the password is not empty so I will have it and  in that case what we will do is we are going to   send a response status as 400 so the validation  is failed and we will send a we will throw an   error actually so I will have the throw new error  so we will have an error object and then we will   have all fields are mandatory so before creating  a user what we will see is we are first going to   check that whether the particular email address do  we already have an existing user in our database   or not so what I will do is I'm going to have  a constant user available and then I can make   use of an await keyword and then we can use the  user model in order to interact with our mongodb   database so let's import the user model first  so I will have the constant user and this will   be equals to the require then I'm going to have  the dot dot slash models slash user model and we   can now have the update we can use the user model  and then we can do a find one and this is going to   help us to find a user which is already have in  our database with the email address so let's use   this email address and check so I'm going to add  it here and now if we have the email address so we   need to pass the email address in an object so let  me have an email address as an object and now if   we find this user available so let's go here and  let's have a check on that so if if we have a user   then in that case we are going to throw an error  which will again be a validation error and we will   have a status as 400 and this time the message  will be that user already registered and then   what we will do is if we don't find any user then  in that case we are going to create a new user in   our database so before creating a new user what  we have to do is we are accepting the username   email address and the password from the client  but since the password is a raw password and we   cannot store the raw password into our database so  for that we need to Hash our password and in order   to Hash the password we are going to make use of  a library called Big Crypt so let's import the   bcrypt library so if we go to the packet Json we  see that we don't have a b [ __ ] Library so I'm   going to open a new terminal and then I'm going  to install the B Crypt so let me have the npm   install Big Crypt and I will hit enter so now we  have the bcrip library and now now let's go and   use that so what I will do is I'm going to import  the B Crypt so let me have a constant big [ __ ]   this will be equals to require and then I will  have the big grip and you will find this bcrypt   documentation on the npm official documentation  but I'll show you how we can use it so it's very   simple to use it and what we have to do first is  we need to create the hash password so I will have   the hash password and how we are going to create  is I'm going to create a constant with an hashed   password and this will be equals to so bcrip is  also going to provide us a promise so that's why   we are going to use an addressing a weight and I  will have the bcrypt dot hash and then in this we   first need to pass the raw password so our raw  password is available in the password and then   we can provide the solved rounds so this 10 is  just the number of salt rounds that we want for   the hashing of the password so you can use this  and now if we do a console Dot log then we will   be able to see the hashed password so let me have  the hashed password all right and then I'm going   to use the hash password I will save it and then  what we are going to do is uh let's go and check   first so if I go back here and we have the post  register and in order to register a user what   I will have is I will have the user name okay  and let's have the username as the malvia then   I will have the email address and we don't need  a phone we will have a password and I'm going to   give the password as one two three four five six  now I'm going to click on send so we can see the   logs and when I click on send you will see that  we have the hashed password so this is the hash   password we are going to store in the database so  that we can prevent or we can have the security   of the user password so now let's go back to the  user controller and now we already have the hashed   password and what we will do is now we can create  a new user so I want to to create a new user so   let's have a constant of the user I will have  the user model and that will give me an Access to   create and whenever I want to create a user what  I will have is I'm going to have the username I   will have the email and then I'm going to have the  password so let's have the password and the value   of the password will not be password we are going  to use the hashed password I will save it and then   what we can see is uh once a user is created so I  will do a console log of the user so that we know   that a user is created successfully so I will have  the user created I'm going to have the dollar user   and now we need to send the information to the  user so whenever we need to send the information   to the user I don't want to send the complete user  because this will also contain my hash password   so what I will do is now if we have a successful  user created then in that case I want to have the   response dot status as201 that is the resources  created and then I'm going to pass the Json data   and I want to pass the ID so I will have the user  dot ID and then I will also pass the user email   address so let me have the email address and this  will be the user dot email address and if there is   a problem then in that case what we will do is I'm  going to throw an error so I will have here and I   will have the response dot status as 400 all right  and then let's throw an error so I will have the   new error object and I will say that user data is  not valid so that means the request was not valid   so that's why we were not able to create the new  user all right so now we have done this if we want   to test it what we can do is we can go to our new  request and here we can try to test it so I can   go and send a request and you will see that when  I send a request I get a response back as status   201 created so my resource which is a particular  user is already created it in the database and in   response to that I get the ID of my user which is  created and then the email address now if I try   to submit it once again then in that case we are  going to get an error and that is because the user   already registered and we have made a check here  so if you will see that uh if we have a user and   if we find it one in with the help of the email  address we throw an error that the user is already   registered and now if we want to verify that in  our database then we can go to our mongodb so let   me go to the mongodb and this is our collection  and inside the users if we go and then we will see   that this is the user we just have created so this  is what uh we have now the register user we now   need to create an endpoint for the login so that  whenever a user is login we get an access token   and for that we are going to make use of a Json  web token so let's go back in our Visual Studio   code and here what we will do is before using the  Json web token I want to go to the Json web token   website site and I want to show you something so  I will go to the Json web token.io and then what   we will do is uh whenever we have a Json web token  so this is sample Json web token and you will see   that it contains three parts the first part is  actually the header algorithm of the token so   it's have a algo type of hs256 and it's a type  of web token now the next piece of information   which is in the pink color uh that is actually the  payload and that payload we are going to have the   user information that we are going to add in our  token so and the third part you will see it's the   signature verification so this is how a Json web  token is and it consists of three different parts   now let's go and let's add it in our application  so what I will do is let's go and first install   the Json web token so I'm going to have the  npm install Json web token now if we go to   the package Json we should be able to see the Json  web token all right so now let's work on the login   functionality or the login endpoint so if we go  to the user controller and in the login endpoint   what we want is whenever a client is sending the  email address and the password in that case we   need to match the password and then we provide the  user back with a access token so what I will do is   I'm going to have a constant and then I'm going to  have the JWT and then I will have the require and   this will have the Json web token and then I'm  going to go to my login function so this is the   login user function and whenever a user is trying  to log in they send in the request body the email   address and the password so let's fetch the email  address and the password first so what I will do   is I'm going to have a constant I will have the  email and then I will have the password then this   will be equals to the request dot body and then  we will just make a check that if we don't have an   email or we don't have a password I misspelled the  password then in that case we need to the response   status as 400 there is a validation failure  and then let's throw an error so I will have   the new error and then we will have all fields  are mandatory uh but if we have a proper email   address and the password then in that case first  we need to find that whether there is a user in   the database or not so what I will do is I'm going  to have a constant user and then I will have the   update we are going to use the user model and then  we will use the find one then we are going to pass   an email address and this will help us to identify  that user is already present in the database uh or   not once we have the user then we need to compare  the password which is stored in our database and   the password which we have received from the  client so what we will do is uh let's have the   compare password with hashed password and what  we can do is a it's very easy to compare first we   need a user and along with that we will also make  a check on the password so in order to do that we   can use the bcrypt method which is a compare so  let's use that bcrypt dot compare and then we are   comparing the password which we received from  the client in the request body with the hashed   password so that will be the user dot password  and this user is the user that we have stored in   our database and which we are retrieving here we  have the user we can now compare the password with   the user.password and if this matches in that case  what we need to do is we need to provide an access   token in the response so what we will do is uh we  are going to have a response dot status and the   status will be 200 and then we are going to have  a Json and in the Json we are going to pass the   access token so let's have the access token now we  need to know what is this access token is now this   is where we are going to use the Json web token  so now let's have and create this access token   so what we will do is let's create a constant with  an access token and then we can use the JWT which   we have imported here JWT and it has a method of  signing we need to sign a new token for our user   so what I will do is I'm going to have the JWT DOT  sign in and this JWT DOT sign in is going to take   few parameters so it will be an object and we need  to provide the payload so if we go back to our   browser then you will see that we have a payload  and inside this payload we can actually pass the   information which we want in our token so let's  go back and here what I want is my payload will   be the user information which I want to embed but  I don't want to embed the user password so what I   will do is I will have a user object as my payload  and then I will will embed the username so this   username will be equals to the user dot username  I will also have the email address which will be   equals to the user dot email and then I'm going  to have the ID which will be equals to the user   dot ID so this is my payload which I'm going to  embed in my token now the next thing is uh we   have to provide an access token secret so in order  to get the access token secret what we can do is   we can just Define a unique access token Secret  in our environment variable file so let's go to   the environment variable file and here what I  will do is I can simply have the access token   so I will have the access token secret and then  you can define a unique secret key value here so   for now what I will do is I'm going to Simply  add the the page one two three as the secret   but you should not do it when you do a production  level code so what we'll do is I'm going to go to   the user controller and here I can use the access  token rate so in order to fetch a value from the   environment variable we can make use of a process  code module and then we are going to have an EnV   we will have the access token secret so I'm going  to just copy this all right let's add it here okay   so now we have that and there is one more property  which we need to pass and that is the expiration   time of our token so we are generating a token  but we need to also provide the expiration date   of that token so that after this token is expired  users should not be able to use the token in order   to call the apis so what we will do is we are  going to set the expiry time and let's set the   expiry time as one minute so this is just for the  testing purpose we are going to set the expiration   time as one minute and once we have this we have  the access token and let's pass the access token   as a response and if there is a error then we will  have an else and what we will do is we will have   the response Dot status of 401 and that will be  uh that email or the password is not valid so   the thing is that if this is not true that means  we don't find a user or we don't match the user   provided password with the stored password then in  that case there is a problem with the credentials   and we are going to pass 401 and let's throw  an error so I'm going to throw in an error so   let's have an error object and then I will have a  message as email or password oops I made a mistake   password is not valid all right I will save it and  now I can just remove this so I'm going to remove   this and I will save it now let's give a try so  what we will do is uh I will go in the new request   and here instead of the register I will have the  login and I'm just going to remove this username   and now let's send the request so if I click on  the send then you will see that we have the access   token so now we are able to get the access token  now what we can do is a b can use this access   token and can access all our private routes if we  go to the contact controller then you see that we   have all the public routes and now we are going  to make this as a private route so the next thing   what we are going to do is uh we are going to make  all our public routes as a private routes and we   are going to enforce a validation on those public  routes so only authenticated user can access those   private routes so what we will do is first let's  start with the user controller and in the user   controller we will first go with the current user  info now to access this endpoint the current user   info we need an access token I mean the client has  to pass an access token so that only authenticated   user will be able to access this route so what we  will do is let's go to the user routes and in the   user routes what we have to do is but before  we do anything in the user routes we need to   make a middleware which is going to help us to  validate the token which a client is sending in   our request as a bearer token so what we will do  is I will go here and I'm going to change this to   current and then what a client will do uh I mean  the user is going to have this token and they are   going to pass the token in the bearer section  and I will send it here and then when a user   sent the request I have to validate this token I  have to verify that the token is a correct token   and it is associated with a correct user so for  that what we will do is we are going to create a   middleware so that where we can verify the token  so I'm going to create a new file and then I will   have the validate tokenhandler.js and in this what  we will do is first let's import the async Handler   so I will have the async Handler and this will be  required I will have the express async Handler and   then the next thing is we will also need the JWT  Json web token so let's import about that and I   will have the require and then I will have the  Json web token I'm going to create a constant   validate token function so I will have the async  Handler and inside the async Handler what I will   do is I'm going to have the async and we are going  to have the request response and then we will have   the next so this is a middleware and you will see  that we have a very similar middleware as error   Handler also and in the error Handler also we have  the request response and the next and we also have   the error now what I will do is I'm going to  create a token variable here and then what we   will do is whenever a user is sending a request  the token is actually passed in the header section   with the auth field so either you can pass it here  as a bearer token or you can have an authorization   filled here so you can also create a new value  which will be an authorization and then in the   value what you can do is you can use the bearer  and then you can add the token here so either   you do this way or we pass it here in both the  cases we should be able to manage to have a check   on our backend so what I will do is uh let auth  header and this will be equals to the request dot   headers dot authorization so if we have this kind  of an authorization so I will copy and I will add   it here or if a user is having an authorization  uh like this so I'm going to copy and then if a   user have an authorization like this so in both  the cases we will have the auth header and now   what we'll do is that if we have this auth header  then in that case we will also make a check that   we have an auth header that starts from so I will  have the starts with and our authorization header   always starts with a bearer so we need to have the  auth in a bearer token so what we will do is we   are going to go and check for the bearer keywords  so if we have Bearer then in the those cases what   we need to do is let's extract the token first  so we are going to have the token variable and   we need to extract from the auth header so what  I will do is I'm going to make use of a split and   then I will split with a space bar so if we go  here and you will see that we have a bearer and   then we have a space so let's split it with the  space bar and then we are going to use the value   of the first index so if we go here the first the  zeroth index will contain the bearer and the first   index will contain the token so that's where we  use the first index we have the token and now what   we need to do is we need to verify this token so  to verify we will use the JWT dot verify and then   we need to pass the token we also need to pass the  access key so process dot EnV dot access token key   so I'm going to go here I will copy and I will add  it here and the third parameter will be a callback   function so this will have an error and then we  will have a decoded user or decoded info formation   now if we have an error then in that case we will  have a response status as 401 and we are going   to throw an error so let's throw an error so I'm  going to have a new keyword and then we are going   to throw an error as user is not authorized so we  are trying to verify the token but user is given   a token which is not a valid token or he is using  a token from some other users so in that case we   are going to say that user is not authorized but  if a user is using a correct token then we are   going to get the user information so what we will  do is let's have a console.log and I will log the   decoded and I will save it now what we can do is  in order to make use of this validate token we can   go to the user routes so first let's uh export  this so I will have the module dot export and   this will be equal to the validate token so I'm  going to have the validate token here all right   I will save it and then what we will do is let's  go to the user route and in the user route I can   make use of a validate token because since only  current user was the private route so I will have   here the validate token it's Auto imported now  let's go and let's give a try so I will have a   API slash user slash current and when I send  a request then we see that we have a 404 and   that is because the end point for the user current  has a get method so let's change this to get and   I will also go here and let's send the request  and since we send the request we see the user is   not authorized that means the token is either an  expired token or the token is not a valid token so   we first need to fetch a new token so what I will  do is I'm going to create a a new request so let's   go to the client I will have a new request and I  will just copy this all right I will add it here   and I will just do a login of the user first so  let's login the user all right I need to pass the   body so whenever I need to log in I will have the  email address as the page oops I don't remember   the email address and then I will have the  password as one two three four five six so let's   go and check the email address so I will go here  I will have the email address so I'm going to copy   the email address and let's add the email address  here and this will be the email this will be the   password so we have the request body now let's go  and let's send it and we get the access token now   let's copy the access token and now let's use the  current which is a protected route so I'm going to   go to my oh I will just remove this I will go to  the auth and I will add my token here and now I   will send the request and you see that when I send  the request what we see is this is the decoded   user we have so we have logged the decoded user  but we also see that uh cannot set the headers   after they are sent to the client so we are doing  some mistake here and what we will do is uh let's   go to our validate token so I'm gonna go to my  validate token here and we have the decoded user   here so what we will do is in the decoded user we  can have the decoded dot user which will give us   the user information so this is the user so what  I will do is I will append this on my request dot   user and then I will have this decoded dot user so  what I have done here is that uh I have verified   the token and I have extracted the information  which was embedded in the token so the information   which was embedded in the token was the this one  the user information the expiry and the creation   of the token and then I have taken the decoded  dot user and this information I have attached   this information to my request dot user property  and then I'm going to have the next so this is the   middleware so I'm just going to intercept the  request I'm going to decode the token and then   I'm going to append the user information on the  request body not on the request body but on the   request dot user the property and now we will  also make a check that if this we don't have a   token then in that case that means the token is  not provided or the token is or the user is not   authorized so let's have a response dot status  as 401 and we will throw in error so I will have   the throw new error and the error will be that  user is not authorized or token is missing in   the request I will save it all right now let's  go and give a try so I will go back here and   then I'm going to send it so I'm sending it and  I see the token is expired so let's go and have   a new token all right I'm going to copy this I'm  going to add it here so in the bearer token let's   add it and now I'm going to send and you see  that the current user information since we are   not fetching the information from our database but  this is a protected route so if you don't have an   access token you will not be able to access this  route so now we have successfully verified the   Json web token and we have also used it on a  private route now what we need to do is whenever   someone is requesting the current user information  we need to go to the database in the mongodb and   then we need to fetch the information and then  provide it as a response so let's go to uh user   controller back and here what we will do is I'm  going to go and I will remove this and here I'm   going to have the request dot user and that will  give me the user information because if we go to   the validate token then we extract the user  information and we put it as request dot user   so when we have the request in that case we will  just send the request.user so let's go and let's   do so I'm going to send the request and since the  token expired let's have a new token I'm going to   copy this let's use the token in the auth and  I'm going to send it and you see that this is   the information of my current user the username  is dimalbia email address and then I have the ID   all right so the next thing what we need to to  do is we need to protect all our contacts route   so only a logged in user will be able to create  delete update and read the context which they   have created for themselves so what we will do is  first we need to associate whenever you create a   new contact we need to associate that contact with  the user ID who is creating it so let's go in the   contact model and in the contact model we need to  update this model so what I will do is I'm going   to add a new property and this new property will  be the user ID and this ID will be for the user   who is creating the contact and what we will do is  we are going to have a type of this and the type   of this ID will be the Mongoose dot schema dot  types dot object ID because this ID is actually   created in the mongodb and that's where we have  the object ID and then we are going to use is as   required so whenever you create a new contact we  need to always have an i user ID so that's how it   will be associated with the particular user so I'm  going to have it as true and I need to provide the   reference of the model so the model is user so  we have made this first change and now what we   have to do is the next thing we need to go to  our contact controller and we need to make all   the routes as private so I will go to the contact  controller and let's change this to private I'm   going to copy I'm going to add it here I will also  add it here then I will also add it here and then   I will also add it here all right we have it and  now let's use the validate token as a middleware   for all the routes which we have so if we go to  the contact routes then in the contact routes   what we will do is we are going to make use of  a validate token so this validate token will be   used for all the routes so we are not going to  use here validate token for each of the method   but what we will do is is we will have the router  dot use so we are going to use a validate token on   all the routes and let's get Auto imported so this  is also one of the way you can do it if you have   all the routes as protected route and you need  to validate the token on all the routes or if   you have only some of the routes then in that case  you can make use like this all right so now let's   go to the contact controller and in the contact  controller now let's make use of the user ID and   then we do the current operations so the first we  will start with that I need to find my contacts so   I need to find all the contacts with the user who  is logged in so we need to fetch all the contacts   of a logged in user so for that what we will have  is we are going to have the user ID and this will   be equals to the request dot user dot ID and I  will save it and this user ID is the one we have   just added in our contact model so this is the  user ID so now if we go and try but before trying   it what I want to do is I don't want my token  to get expired every time so I will increase the   expiration time of my token so I will go to the  user controller and in the user controller we are   set as one minute so let's make it as 15 minutes  and now I will go here and I will first log in   with the token so I'm going to login all right  then I'm going to have my token and then what I   will do is I'm going to have my contact and then  I'm going to pass this token and now I'm going to   fetch all the contacts which are created by the  user name the page malvia so I'm going to send   it and we see that we get an empty arrays because  right now there is no contact being created for   this user which is the page now the user which  is the page is going to create some contacts so   if we want to create the contacts we are going to  have a post request and in the post request what   we will do is let's have a name and my contact is  uh John so let me create a contact which is a John   Day and the email address of John day is just a  John gmail.com and then we have a phone so let me   have a phone and I will have one two three oops  I will have zero nine eight something something   so this is the contact which the page wants to  create it so we also have a valid token and now   if we send it we should be able to create it so  let's go to our controller first and not in the   user controller we need to go to our oh okay let's  close the packet Json let's close the environment   variable file let's close the contact model and  we now only interested in the contact controller   now in the contract controller whenever we want  to create a new contact what we need is we need   to have the name email and phone number but along  with that we will also need to associate the user   ID who is creating this so what I will do is I'm  going to have the user ID and this user ID will   be equals to the request.user.id since we are  using this as a middleware whenever we have a   request this middleware is going to to decode the  token and then it's going to add the request dot   user property and in the request.user property we  will find the ID and then we can now create this   contact all right let's go and let's give a try  I will save it and now I will go and create it so   if I send the request now you will see that this  is the user ID of the page and the page now have   created a contact for with the name as John day  and now what we can do is we can create multiple   contacts for the page so uh in the next contact  I'm going to create is nikesh G and then the email   address is NYX and I'm going to change this phone  number and then I'm going to send and you see that   we have created a contact now if I want to see  all the contacts which the page has created then   I'm going to send request and you will see that we  have two contacts which is created by the page now   what I will do is I'm going to create a new user  and then I'm going to see that the new user is   able to get all this contacts or not so let's go  back here and let's register a new user so I will   have a new user so I will do the register and I'm  going to pass the user name and the username this   time will be let's have a user as Mark so Mark is  an another user so we will have the email address   as Ma at the red gmail.com and then I'm going to  send it and we see that now a new user is created   which is Mark now let's login with Mark so I'm  going to log in with Mark so I will change the   url as login and I'm going to just remove this all  right I will send the request and we get an access   token so I'm going to copy the access token and  now what I'm trying to do is so now this access   token is for the user the page and if we send  the request he has created two contacts but now   I want to change this for token for a mark and now  this token belongs to Mark and if I send a request   then you will see that we don't have any contacts  because Mark doesn't created any new contacts for   himself so this is how we are preventing cross  user uh trying to access the contacts from other   use users and that's where the authentication is  done the next thing we need to do is we need to   update and delete the contact for a user so let's  go to the contact controller back and here what we   will do is uh whenever we need to get a contact we  can get the contact with the help of a request dot   dot param.id but if we want to update the contact  what we will do is first we are going to fetch the   contact from our database with the help of the  ID and then this contact will contain the user   ID of a user who has created so what we will do  is uh before updating the contact we will make   a check and the check will be that if the contact  which we have just fetched has dot user ID dot to   string and if this not equals to the request dot  user dot ID then in that case we will know that a   different user is trying to update a contact of an  another user so what we will do is we are going to   throw an error so I will have the the response  dot status and the status will be 403 because   a user is not authorized to update a contact of  an another user and then I will throw an error   so I will have the new error and then I will have  the error as user don't have permission to update   other user contacts so we have handled that case  and if it matches so the contact.user ID matches   with the request dot user ID then in that case we  are going to Simply update the contact and we need   to do a very similar thing for the delete also so  I'm going to copy this in the delete also we first   fetch the contact from the database we have the  contact we checked that if the contact is found   then in that case we remove it but before removing  it we need to check that the contact which we   found has a user ID and that user ID should match  with the request.user.id and then we will have   oops we made a mistake so user don't and this  will also users don't so now we have protected   all are crud operations of the contacts with  the Json web token and now if we go and simply   do a testing of it then we see that this token is  for the mark and if we let's go and let's get the   token for the page again so what I will do is I'm  going to have page and I will send a request oops   the email ID and the password is wrong so probably  the email ID will be the page dot malvia all right   now we have the token Now using this token I want  to see that what all contacts this particular user   has so this user has two contacts now a user want  to update this contact so I'm going to copy this   let's have a contact here if I go to the body then  I will have an updated contact as nikesh godekar   and I will make it updated I will send it and  you will see that we have a contact but we made   a mistake because it's a get and we need to make  a put in order to update it and now I will send   it and as soon as I send it you will see that the  contact is updated update now what I will do is   I'm going to remove this then then I'm going to  make a get and we get the contacts back with an   updated contact now I want to delete this contact  so I'm going to copy this and let's have here and   I'm going to delete so let me have this and I'm  going to send direct request and you will see that   it's 200 and hopefully this contact is deleted now  so if I go and try to do a get on it then I should   not be able to found the contacts so we see that  the contact not found now what we will do is uh   let's go and let's fetch all the contacts back so  we don't have any contact so there is a problem so   what we have done is if we go here and if we see  then what we are doing is we are doing the contact   dot remove and that is removing all the contacts  from our database but we only want to remove the   contact for which the user is passing the ID  so what we will do is uh we will have to make   a change here and we are going to have a delete  one and which ID we need to delete is we're going   to have the underscore and then we are going to  have the request.param dot ID now let's give a   try so what I will do is first I'm going to create  some contacts so I will go here and I will send a   post or write a contact is created let's create an  another contact so I will have the next contact as   John day and then I'm going to have this as John  and then I will send it so now if I go and fetch   then we see that we have two contacts and now  I want to delete this uh updated so I'm going   to copy this I'm going to add it here and then  I'm going to go and do delete and I will send it   so we see that okay it's 200 and the contact is  deleted so if we go and do a get we should have   contact not found but if we want to fetch all the  contacts we still should have the John Day so you   see that we have the John Day so now we have fixed  the problem uh with the contact dot remove so we   should use the contact dot delete one so we have  created all the crud API of the contacts so we can   now make use of the contacts API and then we can  manage the contact based on the user so we also   have a register user login user and then once  a user is logged in he can create update delete   and read all the contacts which he has created  and similarly we can now have multiple users and   they can they can manage their own contacts so  that's all I have in this video I hope you liked   the video a thumbs up is appreciated you can also  connect with v my Facebook or Instagram you can   follow me on Twitter for latest update and before  you go don't forget to subscribe the channel and   press the Bell icon so that you don't miss the  videos like this one thank you thanks for watching