Node.js and Express.js - Full Course

freeCodeCamp.org · Beginner ·🔧 Backend Engineering ·5y ago

Key Takeaways

Covers Node.js and Express.js, including building a REST API and a MERN app

Full Transcript

this eight hour course will teach you the fundamentals of node.js and express so you can start creating backend and full stack web apps using javascript this course was created by john smilga john has created a bunch of courses including many of the more popular courses on the freecodecamp youtube channel john's teaching is very hands-on so you will create a bunch of projects while you're learning what's up everybody this is john from coding addict and welcome to node and express tutorial video where we'll cover fundamental building blocks of node and express js framework now since i want everyone to be on the same page we'll start the series with node and express fundamentals and gradually move to more complex topics we will build complex rest api with express.js as well as full-blown mern application in this comprehensive node.js course you'll not only learn fundamentals of node but also many related technologies like express.js framework mongodb as well as mongoose the main goal of the course is to show you how to build modern fast and scalable server-side web applications with node like in all my other courses to solidify our knowledge we'll build a bunch of cool apps and go through the steps of deployment as well lastly let me just say this if you're like me and you enjoy learning new tech by building projects instead of going through the slides you will enjoy this course all right and let's start by answering the most obvious question first what is node.js and even though there are plenty of good answers out there the one that i like the most is this one node.js is an environment to run javascript outside of the browser node.js was created in 2009 and it's built on top of chrome's v8 javascript engine as you probably are aware of every browser has an engine a tool that compiles our code down to machine code and chrome uses one by the name of v8 in extremely simple terms the creator of node ryan dahl ripped out the v8 engine and build node on top of it since the moment it was created node has evolved tremendously and while there are many things to like about node i particularly enjoy large community around node since that tremendously saves time on feature development as well as the fact that with the help of node it's never been easier to build full stack apps since both front end and backend are essentially built in the same language and you guessed it that language is our beloved javascript as far as course requirements go there are not that many my expectation is that you are familiar with basic html elements simple css rules and have general understanding of javascript especially es6 callbacks promises and a sync await since this is a node course and i already have tremendous amount of node content to cover i'm not going to spend too much time on javascript language fundamentals while you can still follow along with the course without knowing basics it's crucial if you want to understand how stuff works behind the scenes as a side note if you need to brush up on the javascript fundamentals i have a youtube channel called coding addict where i post a bunch of cool javascript related content specifically you might be interested in js nuggets playlist where i cover a bunch of useful es6 features as well as asynchronous javascript topics so if you need to jog your memory on javascript fundamentals i suggest going to youtube look for the channel by the name of coding addict and then more specifically the playlist by the name of javascript nuggets when it comes to course structure it goes something like this in first section we'll get familiar with node.js as well as my dev setup in the second section we're going to install node.js and quickly cover some general differences between browser.js and node.js then we'll spend some time on node.js fundamentals in section 3 and after that we'll learn what is express.js in section number four and once we're done with node and express fundamentals so once we're done with pleasantries then we're after the races where effectively in every section after that we will build a bunch of cool node.js apps all right and before we install node let's quickly cover some major differences between browser javascript and node.js so essentially how node.js apps are different from the browser javascript apps and let's start with the biggest one when working on node.js app you have no access let me repeat no access to browser apis since well they don't simply exist in node there is no browser so there's no dom there's no geo location no fetch and all the other cool browser goodies you see unlike browser apps that are interactive for example user clicks the button or toggles the nav and that sort of thing with node we build server side apps and i know it's hard to picture that right now but our node apps will only consist of pure logic without the graphical interface on that note you know how in browser apps we use a bunch of cool things available on the window object yeah sorry to break it to you but that's also not available in node so at no point in the course we'll write document.queryselector all right and once we have covered things that node.js does not have let's switch gears and see some of the goodies that node has to offer for example unlike browser we can access file system info about our operating system respond to network quests just to name a few also another major benefit of node is the fact that it's based on versions so unlike browser apps which depend on the user's browser our node app depends only on node.js version it was built in so in other words if we build a browser app and if our user's browser does not support a specific feature it is our responsibility to fix it otherwise our app might have bugs correct but when we're done building our node app there's no rule that we have to upgrade to a newer node.js version and possibly break our app we simply can keep running our node app in the version it was built in and without any worries go on about our day lastly unlike browsers where modules are optional in node.js you have access to modules by default and it's hard to imagine a node app where you're not going to use them as a quick side note under the hood nodejs uses common js library for the modules and while the general idea is exactly the same as for the es6 modules that we use in the browser syntax is a bit different as far as the install it's as straightforward as it gets just navigate to nodejs.org pick a lts version answer yes to all the questions and if you don't get some weird bugs congrats you have installed node in order to check if everything went correct just type node version in your terminal and you should see the version number if you don't you'll have to troubleshoot the error now as much as i would like to help when it comes to install it's impossible for me to troubleshoot your local setup so when it comes to troubleshooting install errors i strongly suggest using your favorite search engine instead typically within a matter of minutes you'll see a bunch of useful solutions to your exact problem lastly let's also talk about versions as you can see at the time of the recording i have two options 14 lts or 15 current one if you read the note docs you'll see that for production apps they always suggest using lts which stands for long term support and therefore i will also suggest the same but as far as tutorial i don't think you'll have any issues if you use the current version instead now also since you're watching this in the future your version number most likely is going to be greater than 14 basically greater than mine i definitely suggest installing the lts option that's offered to you instead of downgrading to my version and if you're stressing about content being out of date let me assure you that everything we cover in the course will work perfectly fine with your current note version and eventually if some bugs do creep in i will definitely update the course content so long story short just install your current lts version whatever it is and you'll be in good shape so in my case it is 14 i have two big buttons and of course since i would want to go with lts i'll click on left one then notice we are getting the download package and now i just need to go to my downloads and then crack it open and then like i said we just need to answer yes to all the questions so we go with continue continue and yep i would agree and again we just install and then we'll be prompted for our passport and once we add that one we should be in good shape and then like i said once the install is complete and yep we'll move this sucker to the trash then if we go to our terminal and if i massively zoom in and if i type node version there it is i should have my version number which in my case of course is 14. if you also can see the node version in your terminal you are in good shape and you can continue with the videos if not please troubleshoot it because otherwise everything we're about to do next is not going to work since you haven't installed node on your computer install is complete hopefully we all have node on our machines now what what do we do for contrast with vanilla.js it was somewhat easy right we create index.html jam our javascript code whichever way we prefer and browser does the rest it evaluates our javascript code but what about node how do we get node to evaluate our code and effectively we have two options a repl which stands for read eval print loop and cli executable which just means running our app code in node if i have to be perfectly honest reply is for playing around and cli is essentially for everything else in fact this is going to be the first and most likely the only time we'll use a rebel in this course and after that cli is going to be our best friend how do we spin up the rebel well we go to terminal and in terminal we simply type node and then no arguments nothing we just press return or enter however you would like to call the button and that's it now notice we have this little angle bracket that just means that we are in the rebel and once we are in a rebel we can do reply things what would be a first ripley thing we can do well we can simply type our name so cons and the name is equal to john and there it is of course now i can access name and my name is john as you can see you're not going to write anything serious in here and if you have written any vanilla javascript apps you know that of course we can also do the same thing in a browser console so we can also evaluate some code there but of course we're not going to write anything serious in a browser's console so the same thing is for reple yes we can come here we can play around but when it comes to serious applications of course you'll pick a cli executable instead and in order to close the repo we simply go with control and c and as you can see we have suggestion that we need to press it again and now of course we're out of the rebel not bad that bad we now know how the ripple works but what about a more serious node application how do we get node to evaluate our code well we would need to start by creating a project right so back on my desktop i'm going to create a new folder and surprise surprise i will call this tutorial why well because we'll do tutorial things and i'm going to say tutorial now of course if you want you can add node but i'm just going to leave it as a tutorial and then of course we'll have to use our text error in my case like i already previously mentioned i'm using visual studio code and my preferred method is just drag and drop and then instead of the folder what i would want is to create a new file and this is the case where you can literally name it whatever you would want and in my case i'm going to go with app and js and in this app.js okay now we want to write some more serious node program and the program is going to be following where there is a const so there's a variable by the name of amount and as a side note i'll make this bigger and i'll probably bump up the font size just so we can see a bit clearer so we're gonna go with const and not also close the sidebar hopefully you see that i have the file by the name of app.js and like i previously mentioned we're going to have a variable by the name of amount and it's going to be equal to 12 and now let's set up a if condition where if amount is less than 10 then we simply cancel log small number and otherwise we'll just say that the number e is large so we go with if and we're looking for amount is less than 10 and if that is the case we go with console log and we'll just say small number and otherwise if it is of course equal or bigger than 10 then we go with console log and we say large number and at the end of the day we just write console log hey it's my first note up as you can see an extremely complicated functionality and in this case i'm just going to set up the template strings so you understand that of course we can use them here as well i'll say hey it's my first node app and if you want of course you can jam the hello world there somewhere as well since that is the traditional approach with the first program and then in order to execute this code we effectively have two options i can navigate back to my terminal and i can zoom in like so and of course now i'm in a root so i would need to navigate to the desktop and probably the fastest way is just typing cd and drag and drop my folder here okay so now as you can see i'm in the tutorial and in order to execute my code i just need to type node and then app.js now keep in mind that technically i could have done that from the root we just need to provide the full path where i go to users blah blah blah and then tutorial and of course the file name is app.js and let me bump up the font size even more and the moment we run it check it out we have large number and hey it's my first note app now if you don't believe me we can go back and we for example can say that the number is nine and of course again we would need to run the code and we're gonna go with node and then app js beautiful we have small number and we still have our hey it's my first node up again the whole point of this line here is just to showcase that not only we can use quotation marks but also we can use the template string as well so that's one option but if you're familiar with vs code you know that it has this cool feature of integrated terminal where effectively we have our terminal but it is right away pointing to our folder so we don't need to do this whole dance where we navigate to the folder and then run the app we simply can open this up and the shortcut is control and tilde and also keep in mind that of course you can navigate through the tabs the problem is that i always forget where it is and effectively we need to go to view and then you're looking for this terminal command here as you can see this would be a shortcut and tilde and in here we have nice suggestion that we already located in tutorial folder and what do we need to do well again we just go with node app.js why well because that is my file name so for the remainder of the course i'll use the integrated terminal that comes with this code just understand that both of them effectively do the same thing and there it is now i run node app.js because that of course is the file name and i have small number and hey it's my first node app and that's how we can evaluate a more serious code using node as i note if at any point during the course you need to compare your code to mine just navigate to website johnsmilk.com and the website is johnsmega.com and then either in the project page or in the homepage you'll find node express tutorial project so in the homepage you'll find it in the latest project so just keep on scrolling but if it's not here it's definitely going to be in the projects page and you can even filter it in order to save some time so look for node in here like i said the project name is node express tutorial and not any of these links will get you to the repo and at this point you can either clone it 4k or just simply download and you're looking for this node tutorial and in here you'll find all the folders as well as the files now keep in mind that eventually when we start working on express we'll have to get this repo anyway because i'll use it for starters since i have prepared some assets for you some assets that we're going to use in our examples so this is really up to you if you want you can get it right now just keep in mind that you'll have to get it later anyway and once we have executed our first code in node let's quickly cover the concept of globals or global variables in node and the emphasis is on the word quickly yes there are more global variables available but the idea is not to spend half an hour in slide bill instead i would want to give you a general idea and as we progress with the course don't worry we will implement them and that way you can right away see them in action not just some random general description and before we continue let me just mention that throughout the tutorial the code from the previous video i'm going to save in a file so for example remember our first complex app with a mount and all that so what i did i created a file name by the one hyphen intro js and then i just copy and paste it this is what i'm gonna do throughout the no tutorial part of the course so that way you can always have access to the code and if you ever need to you can jog your memory now if you don't want to use my one if you're adding your own comments and all that i would also suggest doing that where essentially just create a file just dump it and then that way you are slowly progressing on the course and if you ever need to go back and refresh your memory you always have that option and keep in mind that if you would want to run this file you simply go with node and then whatever the file name right so in my case that would be one dash intro js again i'm going to keep on numbering them because i'm just annoying that way but you don't have to that is really up to you so back to the globals when we work in vanilla.js applications we know a very cool thing is the fact that we have access to the window object and the reason why it's so cool because in the window object we can get a bunch of useful things right so for example we can get a query selector so i can select a node i can get built-in fetch and hopefully you get the gist now i don't want to rain on your parade but you know there's no window why well because there's no browser so there's no window object so if you'll try to access window node will spit back the error and most likely your app will crash now there are some globals of course there is this concept of global variables and essentially what global variables means that anywhere in your application you can access them so no matter how complex my application gets how nested it gets or whatever i'll always have access to those variables and again let me repeat these are just some of the variables of course there's more and i'm not going to spend hours and hours talking about them i simply want to give you a general idea and then like i said we'll start using them and you'll see them in action and in my opinion that's just going to make it way clearer about what in fact they're doing and some of the useful ones we have their name so that would be underscore underscore their name just going to give us path to current directory then we have also underscore underscore filename which as you can see is going to give us a file name then we have require which is a function to use modules as well as the module that would be info about the current module now these two will literally cover them in the upcoming videos because our next big topic is going to be modules so for time being just remember that we have require and module and you'll see them in action in no time and then we have a very very very useful one and that one is a process and why it's so useful because it gives us a info about the environment where the program is executed because we need to keep in mind when it comes to a node app at the moment yeah we're executing that on our machines but when you deploy for example your api so for example your server right where is it sitting it is sitting on digital ocean or herald core or whatever so that of course is already a different environment and of course based on that environment you can make a bunch of decisions in your application again if you'll take a look at the process right now it's just going to be a giant object of gibberish data but trust me as we're progressing we the course will find a bunch of useful properties that we'll implement in our application now any of them you can simply console log and you'll get that useful data so you can just run console log and then for example their name again i'm not going to cancel log all of them probably the biggest one is going to be the process like i said you'll get a bunch of properties that at the moment will look like a gibberish and i simply need to save and of course then we go with node and app.js we run that and there it is now of course this gives me the path so if you're interested of course you can console log rest of them as well but in my case i'm going to stop with their name now also very quickly yes you have access to the console so as you can see in order to cancel log we have to use the console so that is also something that is available globally then just like in the event ljs we have set interval as well as set timeout so you can run these ones and i'm not going to run both of them but i'll show you set interval very quickly just so you don't think that i'm cheating and the way it's going to look like of course we have our callback function and then i'll say that my interval is going to run every second and i must type hello world otherwise well what kind of tutorial is this and again we simply go back to node and then app js and as you can see now after every second i have hello world in console and in order to stop it remember the command was ctrl and c and before we move on and start talking about the modules let me also mention something else where essentially we don't need to type node and then app.js you can simply write node and then app however throughout the course i'll probably keep on typing js just because i'm annoying that would be the first thing now the second thing and this is not a node thing this is actually a terminal if you don't want to type it you can simply go back to the previous command and in order to do that you need to press on arrow key up and check it out the moment you press notice that was my previous command and then i have one before that so in my case that is node and then app.js again you don't need to add that just extension but probably i will and then you just go back to the previous command and then press and again you just execute that command and of course if you want to clear the console again this is not a node thing this is a terminal i just type clear and lastly to answer the question that's probably bugging you the most we always have to just type node and then the file name because as we're going to be testing a special in tutorial it will probably get annoying and the answer is yes but only for now once we learn about npm the external packages which at the moment i fully understand doesn't make any sense at all then there's command that effectively will restart our application so we'll have to install some third-party module some external library and that will do the job of restarting the application for now yes all throughout tutorial up until the point where we cover that external library and external libraries in general yes we'll have to type node and then whatever is the file i know it's a little bit annoying but i just don't want to skip ahead i want to get us there with a full information of what is happening so with this in place with clear understanding of the global variables in node now let's move on to our next topic which is going to be modules in node beautiful and once we understand the globals in node now let's talk about the modules and first let's return to this command notice we have here node and then app.js probably the question that you have is well does that mean that all my application needs to be in this one file and the answer again is yes and no yes you'll execute one file but you'll split your code in modules otherwise that would be literally insane to jam all your code in one file and effectively i'll just show you with an extremely complex app and of course extremely complex is in the air quotes right now and you'll see why we'd want to use the modules in the first place so in the next video i'll give you official intro with a bunch of gibberish and all that but for time being let's just build super complex app and then see why i would want to use those modules in the first place and if you have any familiarity with es6 modules if you have worked with them in vanilla.js or in react.js you're already in good shape the syntax is going to be tiny bit different because you know it uses common js but the general idea is exactly the same and we start with a simple function by the name of say hi you guessed it and then this function is going to be looking for the name parameter and then inside of the function what do we do we simply cancel log and we say hello there and then whatever is the name of the dude or the gal that is being passed in as a parameter and of course we can invoke it and i can say say hi and then pass in susan for example and in order to make this interesting i'll set up some variables as well so i'm going to say const john is equal to john and you guessed it since there's a john there also has to be a peter and hopefully you get the gist so imagine we would have a bunch of names and then we have probably more functions than this one but for time being this is just going to be say hi we copy and paste we invoke this function i guess three times one for johnny boy one poor peter and then the first one we already have for susan and what do we do we run node app or app.js we run that and there it is now of course in our concert we can clearly see hello there susan blah blah blah now wouldn't it make sense if the names would be separate as well as this function or the future functions that we're going to create would be in separate files and then we can access them all throughout the application and that way of course we would have smaller files and more structure to our application and that is exactly what the modules allow us to do and that's why we'll move on and start talking about the modules in the next video beautiful and once we understand the main problem with this code where again the moment code is technically still tiny but as you can see it is getting bigger and more annoying with every line now let's talk about the modules and i guess let me just give you the main idea first and then we'll talk about the implementations and all that good stuff so first of all what are the modules again if you're familiar with es6 modules you already have the idea but essentially that is encapsulated code and the key here is that we're only sharing what we want so we're only sharing minimum how would that look like in real life well i can go here with secret and then i can type here super secret and then since this variable is in this file as we can see you can access anywhere okay so by mistake i can just access it i can override it now of course you can make an argument that i mean it is made with cons but hopefully you get the gist this is available to me everywhere in this file so once we set up the module you'll see what are the differences now node uses common js library under the hood that's what makes it happen and then every file in node is a module again let me repeat every file in node is a module so those super powers that we will cover in just a few seconds we have them by default we don't need to do anything we don't need to go to the store and buy some javascript code no we just get them by default and the way the modules work well we simply need to create a new file right and i'll right away set up the names here because of course eventually this code will be sitting in the file name by the three hyphen and then the module basics or whatever but the names as well as the function well it's going to be in a separate file so what i'm trying to say is that in a root of course there's no folders or nothing so everything is rude i'm going to go with four again i'm doing that because eventually this is going to be three hyphen modules something i'm gonna go with maybe names or you can type first module whatever you would want and i'm just gonna go with names.js okay awesome and then i'll take these three variables from my app.js and i'll copy and paste in the names and then also what i would want is to set up one more file and of course this one will be five and i don't know we can say second module or so i'll say here utils something generic so we set that up and now of course what i would want is to grab this function from the mgs and copy and paste in the utils and now sixty four thousand dollar question is this app gonna work or is it gonna break and of course the answer is it's gonna break because we have no access right now to say hi or to john or peter so why don't we go to the names and console log something and as i said yes you can console log this in the app.js it is a file so by default it is a module but since we'll do most of our work in the names and new tools first why don't we go to names and that way we can also see how we can run the file just by using node and what i would want to console log is the global by the name of module so in the names go below or above the variables doesn't really matter and go with console.log and then module and remember to run node and then whatever is the file name so in my case it is four dash and then names js you run this and you'll notice something pretty pretty cool where we have the object and in that object we have quite a few properties now the one that i'm interested in the most is this exports one and it tells me that this export is an object and the way the common js syntax works whatever i'm going to dump in that export i'm going to be able to access anywhere in the application so that's the key remember we're only sharing the minimum so it's up to us to set those values in that export object we decide what goes in there previously remember secret was accessible everywhere in my app.js now in the names i can be hey you know what john and peter yeah i'm sharing them anywhere in application we can access that but the secret variable no this is just going to be local so i'm going to add here i guess the comment by the name of local and that way at least we understand so this is going to be i mean i'm not going to use global but i'm just going to say that share so we're sharing this with rest of our application and then if i know that this is a object and it is sitting in the module how does that work well we go with module then it is an object so we go with export and we have multiple ways how we can set this up but the most basic one will simply say that yep it is an object and inside of that object there's going to be two properties john and peter now i can probably already guess that we're using a es6 syntax since the key name is exactly the same as the value well we can simply pass it right so we have john and peter so now what happens in the app.js we can access them so i can go back and this is the case where we'll need to run that require remember in the globals we talked about this function so in order to share them we need to use module.exports and essentially i'm setting up the object like so where i go with whatever values i would like to share now in order to access them i need to go with require and i can assign it to a variable or i can simply require now in our case we will assign it to the variable and i'll use the same type of syntax where i'm going to go with names just so we can console.log that and this is going to be equal to require so that's my function and as a parameter we need to pass in where the module is located so where is this data coming from and always always always always you will be setting up your module you have to start with dot now sometimes your modules will be two levels up i don't know three levels up whatever then of course you'll start with dot dot but you'll always start with this one dot because there's also going to be a third party modules and there's going to be built-in modules in node and then we'll use just these quotation marks again super super important every time you create your own module you'll have to start with dot and then forward slash so essentially you're giving a path now in our case what is the path well i'm looking for the names right so i set up here the path and then if i cancel out the names i should see something pretty pretty cool where i go with names and there it is now i'm going to run node and then app js now keep in mind we're not running names anymore we go with node and app.js now of course still complains that we have no access to hi let me comment this one out so let's say node and app.js and check it out now of course we have the object with john john and peter and peter and we explicitly said what we would want to export so we go with exports and that way no one has access to the secret one so this secret one is only for this file and of course we can do the same thing in the utils as well right so we have the say hi and we go with module and export and i can just simply set it equal to now the reason why i was setting this up as a object because i had multiple things at john and peter and don't worry in the next video i'll show you alternative syntax how you can also set this up but in this case i have object and then of course i'm setting these properties and i said note this is just my preferred way of actually using the exports again there's multiple ways how we can do that and i will cover the other ways in next video but this is just my preferred method that's why i right away set my exports equal to an object and then pass these two properties and in utils since i only have one thing i'm just gonna go with say hi that's it i'm saying that i'm gonna be exporting my function so say say hi like so and once i have exported my function now of course i need to go back to the app.js import my function the same name and i'm going to go with say say hi and that one is going to be coming from the different file of course so we go with five and then utils and notice here how we don't need to pass in the js if it is ajs file we just simply omit the extension as long as the file name of course matches and then i can remove now if you want you can cancel log but i already know that i'm gonna have the function over there i'll uncomment my say hi so now of course there's going to be no error and let's make a clear console and again we run the node and then app js and there it is now of course we have a different error where it says well john is not defined all right but i know that john is sitting in the names right so here we have multiple flavors either you can destructure it so instead of going with names i can go john and peter that is definitely one option or i can go with property names right so i can say names and then john and then the second one is names and peter names and peter and now hopefully everything works otherwise you're probably thinking that i'm just messing with you there it is now we have hello there susan john and peter and effectively what we did we separated our concerns again the main idea is that every file by default is a module and then when it comes to a modules we are in charge what we are sharing and in order to export or make it something available from this module we go with module exports and then we just set up the functionality whether this is going to be a object that we're exporting or we're simply exporting as a function so we set this equal to to the exports and if you're familiar with es6 modules as you can see this is very familiar to the export default and then whatever you're exporting as default whether that is a function whether that is a react component or whatever notice i'm exporting as default so of course when i'm importing this in this case app.js well i already know that this is a function so i can name this whatever i would want and the same goes here since i'm exporting this as object i can call this shaken bait as long as i access it later of course i'll be able to access the property as long as the name matches to whatever i set up over here so let me save this and now of course we can talk about our next topic all right so far we know two flavors one if we want to export one value we just set module export equal to that value and then of course wherever we want to use it we just import it set it equal to some kind of variable and of course once we use that variable we have access to that value and the second flavor is if we have multiple values then we simply set module exports equal to an object and then in that object we set up the properties however there's also another way how we can do that and essentially it is called export as you go and the way it looks like first i'm gonna set up a new file and i'll call this six and i'll call this alternative flavor now again naming is really up to you since that is the hardest thing in programming and then i'm going to come up with one array and i'm going to call this items and that will be equal to item one and item number two and then i'll set up a object and i'll say const person is equal to a object and there surprise surprise we'll go with name property and set it equal to bob and i'm purposely adding multiple data types just so you don't think that we can only export variables or functions and in here we have two options either where we are setting up the value in this case items i simply go with module exports and then whatever is the name and of course in this case i'm going to keep the items but notice the syntax where instead of going with const items i right away go with module.exports or if you are a true rebel you can do something like this module exports set up the property for example single person and set it equal to your person object why we are able to do that because if you remember in the previous video when we console logged module exports it was an object right so what are we doing here we're setting up a property on that object and set it equal to an array and here i set up another property and just set it equal to a person keep in mind of course i can still write simply module exports and then the person but since you might sometimes see this type of syntax as well i wanted to cover that and now of course we save alternative flavor.js and you're probably not going to be surprised that if we navigate to app.js and in this case i will call this data because i'm getting a object and on that object i have two properties and i need to come up with some kind of name now as always this name is really up to you you can call it shake and bake you can call it uncle bobby whatever you want in my case i'm gonna go with generic data we go with require again we're looking for the file by the name of alternative flavor and in this case i'm not gonna do anything with it apart from console logging and if i navigate back to my integrated terminal and run the node app.js there it is of course now i have the items as well as the single person now please keep in mind one thing where this syntax whether the first line or line number six at the end of the day is exactly the same like we're doing over here yes the syntax is a bit different but at the end of the day you just make these values available somewhere else in your code now just because i prefer this type of syntax most likely throughout the course you'll see this approach but if you prefer this one instead be my guest at the end of the day it is your application and you are the one who is going to be maintaining it and before we move on to built in modules as well as third-party modules let me throw you a mind grenade and i'm going to start by removing this console log in the app js like so and i'm going to create a new file with the same exact name a mine grenade as always if you would like to call this differently that's totally your option and i'm going to go with mine grenade like so and js and in this file i'll create some basic functionality and by the way let me save app.js so let's go with const num1 is equal to 5 and then const num 2 is equal to 10. of course there has to be a function that adds these values as always with every tutorial so go with add values just for the sake of it i'm just going to go with good old function keyword and the old setup meaning not the arrow function syntax and simply here we'll go with template string the sum is colon and then of course let's go for template literal and we'll say num1 plus num2 and instead of setting up the exports i'll simply invoke add values and now i'll throw you that migrate that i was talking about where in the app.js i'm not going to assign it to anything i'll simply write require and then we'll go with my grenade and now let me comment out these three since at the moment they will just over populate the console and again let's run node and app.js and once we're on our code we can clearly see in the console something pretty interesting where we have a log of the sum is 15. so what's happening over here well when we are setting up everything if we have a function inside of the module that we invoke yes that code will run even though we didn't assign it to a variable as you can see clearly here and we didn't invoke that variable and before we go any further let me mention three things first it's not unique you can also do that in es6 modules and if you took my vanilla javascript course you know that we use that functionality number two yes throughout the course here and there we will use this particular setup now it's going to be with third party modules and of course once we get there i will remind you about this setup so that's how it works and third i wouldn't suggest losing your sleep over it just please remember that when you import a module you actually invoke it and this is really going into weeds but the reason why that happens is because this code is not just exported on its own when the node exports this it actually wraps it in the function so that's why when you're required yeah you do invoke the code if you have some kind of function that actually is executed here keep that in mind not talking about exporting something i'm talking about executing function here and there and of course in this case you need to use the imagination that we'll do something way more useful than this at this point you're looking at it okay i could have just set up that function in app.js and you're 100 correct this is the place where you definitely need to use your imagination where of course the functionality we'll use it for is going to be way more complex but the idea is going to be similar where we'll just require some kind of module and behind the scenes that module will do a bunch of cool stuff okay that was fun we created our first module and in the process covered the general module syntax and use cases as well now what well as helpful as our say hi function is some very smart people created way more useful modules than that and the good news is that we can start using them right away so what i'm trying to say here is that node has bunch of built-in modules that we can use freely in our apps in the following videos we're going to cover following modules os module so operating system module path module file system module as well as http module to set up our http server and before we continue let me just say this i purposely cover only a few major modules and more specifically only a few properties and methods provided by those modules you see the list of built-in modules in node is quite big and the amount of properties and methods each module has combined is of course even bigger and as a result we could easily spend the remainder of the course on just that but is that really beneficial and of course the answer is no instead let's cover the general setup first and later as we progress with the course implement some modules as we go now if you're interested in more properties and methods built and modules have just navigate to the docs and go nuts so if at any point you would want to find out more about specific property or method or the built-in module in general just navigate to nodejs.org and then look for the docs and again in my case the version the long term support version is 14 so i'm gonna click here but as you can see we also have an option of going to the older versions as well so as you can see i can get the docs for the older versions as well but i'm just going to stick with my version and then be prepared to go nuts if you enjoy docs then you have yourself a big old party where of course you can look for modules and then each module has the properties as well as the methods so of course you can get a extremely detailed information on the properties as well as the methods here in the docs all right and once we have covered the general existence of built-in modules now let's take a look at few of them and i'm going to start by creating that file that i promised a few videos ago remember when i was setting up the modules i said that eventually there is going to be a file by the name of 3n modules and this one i would want to do it together just so you don't think that i'm not fulfilling my promises so we're going to go with module and then i guess modules.js i'll grab that i currently have in the address it's pretty much everything and we copy and paste and in this case i also uncommented these say hi again this all stays for your reference and you'll have access to it if you navigate to the github repo so grab everything in app.js i'll actually cut it out since we'll start from scratch and copy and paste now of course all this code is sitting in the modules and just keep in mind that of course we're still referencing the names utils alternative flavor as well as my favorite the mind grenade and back in app.js now let's start by taking a look at the os module and os module we built in module provides many useful properties and methods for interacting with operating system as well as the server and the general setup for the built-in modules or even the external ones that we're going to cover a bit later is going to be similar where we're going to go with some kind of variable and in this case i'm going to call this os for operating system then we're going to go with require and then in the require we'll have to pass in the name so since this is a built-in module of course we don't need to install anything just remember it later when we work with external ones yes we'll have to install that module first in this case it is a built-in so we just go with os but again let me stress something we're not doing dot and then forward slash no we just go with os so that way node knows all right so you're looking for the built-in module and once we set this up then we have multiple options either you can access those methods by just running this variable so it would look something like this where i go with os and notice the moment i press dot i have all these options so these are the methods and properties that i can use or if we know that we want a specific one you can simply destructure it here and of course throughout the course i'll use multiple setups just so you understand that both of them effectively do the same thing so here i have access to all the methods and properties that this module provides and of course now we can go crazy for example i could get a useful info about the current user which of course is me so say info about current and user and you know what as a side note i'll save here and i'll close all the files it's just a bit annoying that i have all those tabs open back in the app.js once i have a comment of course now i would want to assign it to a user and we'll simply go with os since that is the name of my variable and then method that i'm looking for is userinfo i don't need to pass anything i simply invoke it and of course since i would want to see the result i simply go to console log and then i'm looking for the user and you can probably already guess that we'll just run node app.js and there it is now of course i have a info about the user which is me so this would be a home directory this is going to be the default shell and all kinds of useful stuff then i want to show you how we can get the uptime of the system so effectively how long the computer has been running in seconds and i'll just add a comment method returns the system system up time up time in seconds and the way i'm going to run that i'll right away set up the console log just so you understand that of course we have multiple options how we can invoke those methods you don't always have to assign to some kind of variable now i'll leave this one in here so i'll leave the console log and then user and let's say right above or you know what let's do it this way so leave the console log where the user is and then let's go with another one we'll go with console.log in this case i'm going to go with template string and we'll say the system system uptime yes and then let's use a interpolation of course and the method that i'm looking for is uptime so again i go with my variable name and i know i've said this before but i just want to stress this point just so we all are on the same page and in this case i'm going to go with os and then the method name is uptime and then let's just add seconds and again same deal back in the integrated terminal run node and then app.js and there it is now of course not only i have the info i also have the system uptime and what's interesting this actually is 100 seconds meaning if i'll run this notice that you'd expect that this would probably stop at 60 right since we have 60 seconds in a minute but no actually this one goes to a hundred and then i'm just gonna set up a object where i'll show you a few more methods and then we'll move on to a next module because again the point is not to cover each and every method the point is just to give you a general idea how the modules the built-in modules would work in node so clear my terminal and then i'll create a object i'll call this current and then os and then in this object i'll set up properties and i'll set them equal to the method that actually returns that value from my os module so go with name and os and this is going to be equal to a type method then i can get the release and this one will be equal to os and then release again we invoke it then we'll look for total memory and free memory total and mem and of course i'll go with os and then total mam as you can see somewhat predictable and then we're gonna go with free memory and it's not going to be surprised if we're just going to go with free memory here let's save that one and lastly let's just cancel log it and we should get a bunch of info about our current operating system again we're going to go with node and then app.js and not only have the user information not only i know how long the system has been up in seconds i can also get some useful data about my operating system and again we're just scratching the surface of course there's more methods and properties but hopefully you have a clear understanding how powerful these built-in modules are in node.js since the node we can interact with the file system something we couldn't do when we used our javascript in a browser another useful module is a path module which allows us to interact with file paths easily and i'm going to remove all my code in the app.js because behind the scenes i created a file by the name of 8 os and module and of course copy and pasted the contents from the previous video that's why in app.js i'll remove everything and the setup is going to be exactly the same we come up with some kind of name now most likely it's going to be path and then we pass in the module we would want to get and in this case of course it is a path module and then let's just start with a very useful property a separator property that returns a platform specific separator so if i go straight up with console.log and then path sep this is going to return my platform specific separator so if i write node mjs there it is and of course i have forward slash now if you're using different platform for you the value might be different after that let's take a look at the path dot join so the join method which joins a sequence of path segments using that platform specific separator as the limiter and second thing it does it returns a normalized resulting path and in order to show you an example i'll create a new folder so not a new file but a new folder i'll zoom in and i'll say content and inside of this content folder i'll create another one and i'll simply call this generic subfolder and in this subfolder i'll say a test and text file and instead of the text file i mean you can place something you can omit it doesn't really matter i'll just say text and then txt and once we save it back in the app js now i want to use that path dot join method so i'll say const and then file path is equal to path dot join and then we need to pass in those values as strings so for example since i'm looking for the content folder i'll simply say forward slash and then content then i know that inside of the content folder i have the subfolder that's another folder and then eventually there's going to be a test txt so we go with test and then dot txt we save the sucker and then if we'll cancel log the file path we should see the whole path and there it is now of course it is normalized and we get it as a value so we have content subfolder test and txt so if i start adding some type of forward slashes meaning trailing slashes then of course they will be removed we still get the normalized path and we can also get the base name so for example i create this file path but i only would want the last portion of it how can i access it well the method name is base name so we're gonna go with const and base and path dot base name and we just pass in that file path and now if we cancel log the base we should see the text again these are just summaries if you want just a directory of course you can imagine that there is a method that returns that as well but since i don't want to cover each and every method that's why i will skip that one and there it is now of course not only i see my normalized path but i also see the test txt which is my base and the last method that i would want to showcase is path.resolve and why it's so cool because it returns an absolute path and once in a while in our applications we need to provide that absolute path that's why of course we'll have to use that method and when it comes to path.resolve it accepts a sequence of paths or path segments and resolves it into an absolute path so below the base i'm going to go with cons and then absolute and that one is equal to path and we're looking for dot resolve and here remember when we talked about the globals one of the first globals i covered was underscore underscored their name so this is going to point to this directory where the app.js is located and once we're here then of course we just need to provide rest of the values in my case that is content then i'm looking for sub folder and then eventually i would want to get to the test dxd i would want to get this absolute path and then once i set up the value of course if i go with my console.log and if i provide absolute once i run node and objects you can probably guess that in the console i'll have my absolute path to the test txt and if you're wondering why we would ever want that well remember our application is going to run in different environments right so of course the path to some kind of resource is going to be different in my computer in my local machine than for example in heroku hopefully it is clear and now of course we can take a look at the next useful built-in module nice now we know how we can work with path module and like i mentioned in the previous video we also have an option of interacting with a file system so what i would want right now is first create a new file i'll call this nine and we'll say path and module like so js i'll grab everything that i have in the address copy and paste and once we have this one out of the way i'll just remove and keep the app.js clean for now as well as clear the console and yes we have an option of interacting with the file system and the module the name of the module is fs now essentially there are two flavors when it comes to file module we can do it asynchronously non-blocking or we can do it synchronously which is going to be blocking but for time being we'll just cover both of the setups and then later in the course we'll cover what are the differences and why you should prefer one over the other one for now just think of them as different methods but eventually yes we'll talk about it the whole structure of the node and why would you want to use the non-blocking code instead as well as different approaches when it comes to callback functions different solutions and for now i just want to show you both methods essentially four methods and then we'll just move on to the next topic and in order to set this up in this case i'm just going to structure right away the methods that i'm looking for and in the first video we'll take a look at the synchronous ones so that's why i'll destructure read file and sync and that is coming from require and then the module name is fs again please keep in mind it would be the same thing if i were to go like this fs and then fs and whatever the name i was going with read file sync and of course i have access to it i'm just showing you a different way how we can access those methods we just destructure them out of the fs module and then the second one will be write file sync write file sync and then once i have the structured both of them then i'm going to set up two variables so first we'll read two files we haven't created those files yet but in a second we will and then eventually we'll create a new file with write file sync so i would want you to go to the content folder if you haven't created then i suggest creating one and i mean i'll keep the subfolder just because i believe the path module is still using it but in a content i'll create a new file so not in the subfolder but actually in the content i'll say first first and then txt so this by the way sets it up in the content so let me move it up or i'm sorry this sets it up in a subfolder i believe and it tells me do i want to move yes i would like to move and now i have the content that has the first txt and then i have the subfolder with test.dxt of course if you want you can place it in a subfolder that's really up to you but in my case i would want them simply in a content so i'll go the second one txt and as far as the values i'll say hello this is first first text file and then of course we can copy and paste the value and just change it around to the second file so in the second txt we'll say second text file and once we have both of the text files now let's take a look at how we can read from the file system and since we have read file sync we know it is a method and in that method we need to provide two parameters we need to provide a path to that specific file as well as well what is the encoding so the node knows how to decode the file and generally you'll go with utf-8 and we'll first go with first that's my variable we'll go with read file sync my method name and like i said we provide a path we go to the content and then inside of the content there's going to be a first txt and then as far as the encoding the default one will be utf-8 but if you want to be a bit specific just set up the second parameter and notice these are all your options and just go with ut effect okay and then once we have everything in place of course we can copy and paste this is going to be the value for the second one and we just need to change the file name of course so we have the second one and now in a console log we should see both of the text so if i go with console.log first and then second i should have one long text and let's go with node and app.js and there it is i have hello this is a first text file and i also have hello this is the second text file and once i have both of them why don't we create a new file and the method for that is write file sync and the way it works again we provide two values two arguments one is gonna be the file name and if the file is not there then of course node will create that file and you'll see that in a second and the second one is the value that we would want to pass and i'm going to go with write file sync write file sync and like i said first is going to be a path so you can call this third you can call this result whatever you would want in my case i'm going to go with forward slash content and then we're looking for result and then sync and this is going to be txt and then as far as the value if you want you can simply pass hello world and test it in my case i'm going to make it a bit more interesting where we'll set up a template string we'll say here is the result and why don't we use the interpolation we'll say first and second so we'll have first value and then the second value and you know what when we add here colon as well so let's say first and then let's place a comma and then we're gonna go with second again if the file is not there then of course node will create one and if the file is already there node by default will overwrite all the values that are in the file and i'll show you that in a second so i'm going to go here with node and app.js and check it out now i have result sync txt and then inside there i have here is the result hello this is first text file and also have hello this is second text file and just to showcase that if there are some values they will be overwritten by node well if i go with simple hello world and then i run node.js again i have my new result now if you just want to upend to the file well we need to pass in one more argument notice i have the first one i have the value that i would like to set up in a file and the third one is an object basically an options object and here the property name is flag and if you'll set this flag equal to a then node will append this and the easiest way for me to show you that is run node.js and now we should have two results so we have here is the result and notice how we're starting a new line why well because by default we are overriding everything and then when we add that flag then of course we create a new value so these are two very useful methods that we can use with node to read files as well as create ones from the scratch beautiful and once we have looked at the synchronous approach like promised i also would want to show you the asynchronous and as always let's start by creating a new file again in my case that is going to be 10 hyphen and then i'm going to go with fa sync and js and of course i'll grab everything in the app.js and then just copy and paste and then back in the app.js i would want to change these names so i'm not looking anymore for the read file sync i'm actually looking for a method by the name of read file so this is going to be the asynchronous one and the same goes with writefile now of course we can remove all this code as well and the way the synchronous method works we need to provide a callback and if you're familiar with callback essentially what it means is that we run that callback when we're done so when whatever functionality we're doing is complete then we run that callback just like we normally would do with add event listener on a button remember we go with add event listener we add whatever the event of course with the button that would be a click event and then pass in the callback function and that callback function will run every time we click on a button so this is the same thing where we have the read file function and we can simply use it since of course we have the structured then we need to provide a path so again we go with forward slash content and then the file name is first txt and this is where we provide that second argument and that is going to be a callback mission now in that callback function we pass into more arguments first one is going to be error if there is one as well as the result and then inside of the body first i would want to check if there is an error and then i can just return null as well as maybe console.log so we go with if error and then we'll say return null or simply return whatever you'd want and if you want you of course can cancel log the error as well like so and then if everything is correct well then of course i'll have access to my data which of course has the name the parameter name of result and since i would simply want to console log the result i'm going to go with console.log and the result but of course keep in mind that this is where you would set up the functionality so let's go back and we're going to go with node app.js and in this case something really interesting where we don't get the text right so we're getting this buffer so this is what's going to happen where if we don't provide that utf coding then of course we'll get the buffer now where do we add this encoding value well right here in between in between the content as well as the path so let's just go with string and we're looking for the utf so let's say utf-8 and we'll save that one and let's run it one more time and of course i have node app.js and then hello this is the first text file and now the million dollar question well how we can set up the same functionality check it out we have read file read file and then we simply create a new file with both of these values so if you're familiar with callbacks you know that of course we would need to set up that functionality inside of this callback where i'm getting this result otherwise there's going to be an error because the only way for me to access this result if i'm setting this as a callback is of course inside of this function and this is what i was saying before where yes eventually i'll show you a different approach because inevitably we'll set up a callback help and you'll see that in a second so what i would want to do right now when i get back my first text file well now of course i would want to assign it to some kind of variable and then i would want to read that second file right and then eventually once i read the second file then of course i would want to create that new file and the way it's going to look like i'm going to go with const and i'll say first and you can name it first text i'm just going to know it first and this will be equal to my result okay awesome and then right after that result again i'm going to go with read file and then the same thing we provide a path so we go with content and then in this case of course we're looking for second and then txt then we need to provide the encoding so node knows how to decode that and we go with utf-8 and then of course we need to provide our callback again same deal we go with error and result and in order to speed this up i will copy and paste so just grab everything starting with if and ending with the result copy and paste again this is the case where we're checking for the error first if there is an error we cancel log it and if everything is successful we assign this one to the second one and then eventually now i would want to set up my right file so again it is a function we need to provide that value and we already have result sync txt that's why i'll create a new one and i'll call this result and async so again we're looking for the content then we go with the filename which is going to be result and a sync and txt of course since there is no file node will create that for us i'll right away set up my data now if you want of course you can copy and paste this functionality this is totally up to you where basically we use two of them and in my case this is exactly what i'm going to do in order to speed this up if you want to create something from scratch of course that is also an option and i'm just going to copy and paste that's my template string and again if you want to add this flag you can definitely do so in my case i'm just going to omit that so here's the result i have first and second and the reason why i have access to them because of course i'm looking in the outside scope of this callback function and then again we have a callback function in the right file i know there's tons of callback functions that's why we'll have to set up a better setup when we're handling these callbacks but we'll do that a little bit later so for now let's just add a comment here where we have first parameter second parameter and then third parameter and of course this is going to be again our callback where we have error and result and then inside of this callback finally we can take a look at the value and of course the value will be in this result now of course we're creating the file and all that but hopefully you get the gist that if you'd be doing something where you're looking for this result of course it would be over here so again let's check for error quickly if there is an error then of course i would want to return as well as console log the error just in case and if everything is correct let me just console log the result so save it here and two things we need to watch out for maybe there's an error and second one we should create a new file by the name result and then async txt let me clear the console and we're going to run node app.js and i do get an error and error simply tells me that i did not add the dot in front of the content so i would need to go back to write file and just add that and once we add the dot we are going to be in good place where i'll clear the console and i'll run one more time node app.js and then the result will be undefined okay that's fine like i said in this case we're not expecting anything back but what's really cool that in the result async we should have our text here is the result hello this is first text and then the second text so hopefully it is clear this is how we would use the async pattern so let me zoom out right now here and you'll see this famous callback hell and in the next video i would want to give you a brief description of what are the differences between the asynchronous approach or non-blocking approach and the blocking one the synchronous one as well as what are the alternatives to this callback l all right and just to give you an early taste of the differences between the asynchronous or non-blocking and synchronous which is a blocking code why don't we set up few console logs now before we do that i will create a new file and i'll say 11 here and by the way i definitely need to zoom in just so you don't think that i'm cheating fs and async js and let's go to the address we'll select everything and copy and paste and of course in next video we'll set up different module in this appdress so for time being i can just remove it and then like i promised we'll set up some console logs so why don't we go back to fs and by the way during this video i'll zoom out because i definitely wanna go back to this evil evil callback hell that we're getting from nesting callback within the callback and as far as fa sync let me zoom in and why don't we set up a console log in few places let's say before we're accessing the file so i'm gonna go with log and we'll say start then we're gonna go with write file sync and then right after that we're gonna say i'm done with the task and then inside there let's write done with this task copy and paste and we're gonna go with starting the next one starting the next one meaning the next task so that should do it and of course i need to go with clear so clear my console and i'm gonna go to node and then the file name is 10 iphone and then fs and we're looking for sync i run it and notice something interesting where i have the start so that is going to be before i read the files and only then once i'm done writing that file i have done with this task and starting a next one and what we need to imagine that of course this task of getting those files as well as the second one of setting up that file well it might be very time consuming right and imagine that if we have even 10 users and they're all the time using our application and if for example this one user does this one task or both of them and they take really long time what means that node is not going to be able to serve other users and trust me it is at the end of the really really big deal and notice how javascript is reading this code synchronously it just goes line by line so we start with this task then we read these files and then we write the result and again if this is something that takes really long time then pretty much your application is down so no other user can do anything with that application because one of the users is for example reading these two files and then writing one again this is a very simple example but you need to picture that of course there's going to be tasks that take longer time and as an alternative let's take a look at the async approach so here again we'll set up some simple console logs and again we'll cover this in a bigger detail a bit later for time being let's just set up console logs and you'll see the biggest difference where i'm gonna go with log and let's say start so i'm gonna do that before i read this file and then i would want to go inside of the right file the last one and instead of console logging result which of course is undefined since in this case we are not getting anything back now i want to go with done with this task and then right after my first read file i'm going to go with log and starting next task hopefully you're able to follow along again before the read file inside of the right file and then right after the first read file because of course the other ones are nested inside of this callback and then if we go to node and if we just change it around to 11 and then fa and i believe it was async and if we run it notice something cool where i have my start and then i right away have this starting next task and eventually i have this done with this task so what this means is that since we have this asynchronous approach the moment we start this task we just offload we just offload this task and we continue with our code so that way when user number one for example comes here and wants to get this functionality yeah sure here node just offload this task and then your application can keep on serving other users again it seems a bit trivial at the moment because we have a basic approach but hopefully you get an idea where in one case we have everything happening line by line so only when we're done with the task we're starting a next one and with this approach we start a task and we just offload that task and then we start a next task right away and eventually yes we have done with this task in the console as well now as far as the implementation as far as the callbacks yes this is a bit messy right notice how we only want to accomplish few tasks and it's already somewhat off a pain now alternatives are using promises as well as async await now again hopefully you understand that when we talk about reading the file as well as the writing or file i use this as an example of some kind of task that would take a long time now for the remainder of the course mostly it's going to be reading from the database writing to the database and that sort of thing but this is a very good illustration of how some tasks would take some time so of course we would need to use a callback and as far as the callbacks yes you can use them but the code is going to get messy somewhat quickly that's why a bit later in the course we'll take a look at the alternatives which are promises and a sync await and i have to tell you honestly for the remainder of the course we'll use async await because in my opinion it is just easier to work with excellent and up next we have http module but before we continue let me just mention that i purposely won't spend too much time on explaining every single http method we're going to use in great detail and here's why you see starting from next section all of our work meaning code in some shape or form will revolve around server setup aka http module so that point of course i will cover every last bit of syntax in great detail at this point though i think it's just a waste of our time so if you're confused about something http related don't sweat it we will return to that subject shortly and cover it in far greater detail now if you're wondering why we bother with http module at this point at all since we're going to use it later anyway you see with the help of http module i believe i can show you some core features of node in action and give you somewhat of a visual representation of them otherwise i would have to base everything on slides and i don't think it's the best approach so long story short if you're iffy about something http related just please be patient and i'll answer all your questions in the next course section nice i think we've got a good initial understanding of how the file system module works in node and hopefully i did not lose too many of you so hopefully there are still some students left in the course because i fully understand that seeing this for the first time is probably a bit overwhelming and what i would want to do next is cover the last initial module the built-in module and that is going to be the http module which is going to allow us to set up a web server now please keep in mind one thing we'll just cover the basics because the large part of this course is going to be creating your own server and setting up the api now granted we will use an abstraction on top of the http module and that is going to be the package by the name of express but the whole point is going to be exactly the same that's why again we're not going to cover everything in greatest detail at the moment because i don't see the point of repeating myself and now i want to go back to objects i'll zoom back in just so you can see better what is happening by the way let me check my zoom level so i'm going with settings and i think that should do it my zoom level is two at the moment and then back in the app.js let's grab the http module and we'll assign it to some kind of variable as always let's go with require and we're looking for http that's the module name and the method we would want to use is create server again we'll assign this to some kind of variable and in this case the variable name will be server then we go with http create server and this create server method is looking for the callback and in that callback function we have two parameters and both of those parameters are objects and since they're parameters you can call it whatever you would want but a common practice is calling them rec and res now this first parameter represents the incoming request so imagine a client is requesting from the web browser your webpage so you'll have information about the method and all kinds of useful stuff in that request object and the response is what we're sending back now we're not done of course we'll set up more code here but before we do anything we also would need to specifically say what port our server is going to be listening to and that's why we'll go with server and listen so that's another method and again this is arbitrary but i'm gonna go with 5000. again if this looks like a lot of gibberish where we have the request response as well as the ports don't worry later in the course i'll cover that in more detail as well as show you some useful slides and all that good stuff and as far as the response well we have few methods we have write so we go with arrest and again this is the object and notice here how i'm not using the rack yet so i'm not checking for anything i'm just concerned about my response and the method name is right and inside the right we just come up with some kind of text and i'll say welcome to our homepage homepage and once we have sent back the response i also would wanna end my request so i'm gonna go with res.end and once we're done setting up the code inside of the callback function now of course i would want to open up my terminal clear everything and we would need to spin the sucker up and of course the way we do that is node and then objects since that is the file name make sure that you save it though so before i run i'll save it and then notice something interesting notice how we're not exiting so previously every time we ran the file every time we ran node and then whatever the file name we exited from the file right so node was done executing the code and we just moved on now in this case since we have a web server what do web servers do they keep on listening for requests and actually you want your server to always be up and of course if i go to my web browser and then i'll make this bigger and if we go with localhost and of course in this case we have 5000 there it is we have welcome to our homepage so now of course we have effectively created our first website now granted it's very basic but at least we have something on screen and before we discuss the external modules and actually set up a module that nicely watches our code and does the restarts for us i also want to showcase what we have in the request object now this is going to be a giant object so i'm not going to cover each and every property however i would want to showcase a property that gets us the url and what would be the url well that would be an address and if you're worked with reactor or dom you know that for example for the homepage we used forward slash and then if the client wants to go to for example about page he or she would enter forward slash and then the about now in our case notice how we're still serving the same content so just to give you a quick introduction of the request object as well as set up a bit more realistic application we're going to go with the request now again if you want you can log it so we're going to go here with request and you'll see that it is a giant object now since we made some changes we do need to stop it and then we'll go with node object but notice how we're not right away console logging the request object why well because server is waiting for those requests so we need to go back to our browser and then refresh and then of course once we navigate back like i said this is going to be a giant object which bunch of useful info now what we're looking for is the url property because that url property is going to tell us well what address client is requesting so what endpoint the client is requesting and like i said for the home page the common practice is using simple forward slash so in here we can set up the if statement where i say if request url is equal to the home page then of course this is what i would like to send back and just to speed this up i can tell you that we can cheat a little bit where we can just place everything in the end and in my case i'll just cut out my string so we have res dot end so now we simply send the text and now of course i also would want to check for the about or contact or whatever so in here let's go with if and then request and url and if that one is equal to about about then of course i can send different text and as far as the text i'm just going to say here is our short history and then lastly well what happens if the user is trying to access a resource that doesn't exist on our server so we'll have the about page we'll have the home page what about if the user is asking for a contact page that we don't have well here we'll simply set up a default response we'll say res that end and just to make it interesting i'll set up the template string and i'll show you that if we really want to we can also pass indirectly html and i'll say oops an explanation point i'll close my html again please understand this is just a basic scenario of course that's not how we'll be setting up our apis or nothing like that but just to give you a quick intro we'll do it quick and dirty where there's going to be a paragraph and we'll say we can't seem to find the page that you're looking for page you are looking for looking for and at the very end i would want to set up a link that allows the user to navigate back so go with href and i'll say forward slash which just means home page and we're gonna go back home let's close our link let's save that one so at the moment of course we have the about and by the way almost forgot yes we do need to stop the server and we need to go with node and then app.js refresh one more time there it is notice how we don't have the about we can't seem to have the page you're looking for and that is actually a bit interesting because it should be available right and of course the reason is because i messed up on the url property my bad let me do this one more time and we'll stop the server here again let's run node app.js and now we should have here's our short history that's our about page then we have the homepage and of course you already familiar with our error page so if i'll go with error or any kind of resource that doesn't exist then of course we'll get the error page and of course we can bravely navigate back home and we go back to our home page that should do it for the quick intro of base modules and now of course we are ready to move on to our next topic all right at this point we're familiar with two types of modules our own as well as the nodes built-in ones but just like in any good infomercial i'll say but wait there's more we also have access to the world's biggest code store and before you seriously start questioning my mental state imagine this scenario you're building an app and of course as any good app it needs to have a slider just for funsies now at this point you generally have two options build it from the scratch yourself or search on google and copy paste someone else's solution well have no issues with either of these options keep in mind that someone somewhere has struggled with the same issue the need for the slider and there's a good chance that that person was kind enough to build it and share the whole project with us so our only job is to go through the docs and with the help of one command just add it to our project we can do that because when we install node we automatically also install npm or node package manager and npm enables us to do three things reuse our own code in other projects use code written by other developers and lastly share our own solutions with other developers as well the npm project is hosted at npmjs.com again the site is npm.js and here you can find everything starting with useful utility functions to full-blown frameworks and libraries and as an example if you're familiar with react you know that react has the create react app package and of course it is hosted on the npm a typical node project will have more than few npm packages installed as dependencies and before we install some cool packages let's talk about naming npm calls the reusable code a package and a package essentially is a folder that contains a javascript code now another names you'll hear are modules and dependencies and honestly at this point all three are used interchangeably when talking about shareable javascript code so don't be surprised if during the course i call them any of these names package dependency or module at the end of the day they all mean the same thing lastly let me just mention two things first there is no quality control in npm registry anyone can publish anything so it's up to you to sniff out the empty and useless packages and yes there are quite a few of those ones out there as well a good indication of the security and usefulness of package is the amount of weekly download if the number is high meaning if it's popular it's a good chance that it's a battle tested and ready to go and that brings me to my second point remember the slider example we discussed in the beginning of the video when it comes to npm packages there's a good chance that if there is a bug someone else has already fixed it and as a result it's already fixed in the package or there's a working solution all right so that you did for intro let's start using node package manager in our own project and as a side note if you want to search for some packages just visit npmjs.com and then for example if you're looking for the bootstrap you'll find the package and of course you can click on any of them this will bring you to the docs as well as weekly downloads and rest of the stuff once we're familiar with node package manager let's see how we can start using it in our own project and the good news is that it's much simpler than you would expect you see when we install node we also install npm and because of that we have access to npm global command and you can check the npm version by running npm version in your terminal just keep in mind that the version most likely won't be the same as your node version and that is totally okay so you can either do that in the terminal or of course in the integrated terminal and you can simply type npm and then hyphen hyphen version i believe you can also check by hyphen hyphen v and there it is of course now we have the version for our node package manager and then we have two flavors we can install package as a local dependency and that just means that we'll only use that package in this particular project that we're working on and the command for that one would be npm install or i for short and then whatever is the package name so whether that is bootstrap low dash express or whatever or we can install dependency as a global dependency and that just means that we can use it in any project and the command for that one would be again npm i or install whichever method you prefer and then hyphen g so this is going to be the flag and then again the package name now when you install something globally most likely on a mac they will ask you for the sudo so you'll have to provide the credentials that's why you'll run sudo npm install and then hyphen g and again package name as far as which one you'll use more often that definitely will be a local dependency flavor because even though yes you can install packages globally with arrival of npx there's actually less and less need for setting up something globally that's why we'll focus on local dependencies first how to set it up in our project and then in a few videos when we talk about npx i'll cover why there's less need for setting up something globally now there's one more thing that we would need to set up in our project as far as dependencies so i know i know you're eager to start installing the packages but let's just wait a little bit and next video we'll add that extra thing that we're missing right now and then we'll be in good shape and then we'll start installing every package under the sun excellent we now know that we have access to the npm global command we now know that in order to install the local package we will need to run npm i and the package name so what are we missing well we're missing file by the name of package.json and essentially you can think of it as a manifest file that stores important information about our project and there are three ways how you can create package.json first is the manual approach where you just create a package.json in the root and please do that in the root if that's something that eventually you decide doing and then of course you would need to create each property or there are two ways how we can automate this and the first one is running npm init and in there they'll just step by step ask you the questions and if you want to skip it you can just press enter and the another way the third way is running npm init with a y flag and then everything is set up as default so i'm not going to show you the manual approach it's just too time consuming and we'll right away go with npm in it first i'll show you the step by step approach and then of course i'll show you how everything is set up by default using the y flag so go to your terminal and just type npm in it and there it is of course now they tell you that there's going to be a walkthrough of creating a package.json file and the first one is the package name and by default of course it is going to use the folder name now keep in mind that if you eventually want to publish this package then the name has to be unique so you need to make sure that nowhere in the npm you can see the package with the same name and i'm just gonna go with tutorial as far as version we'll talk about versions shortly so i'll just skip this one as far as description whatever again is just the default now as far as the entry point eventually will change it but for now it's good enough we're going to go with one intro js and then the test command as well as git repository and keywords and author and license and we simply say yes and we are in good shape so now of course we have the package json file with name version description as well as the main property and of course the scripts author and the license now i'll remove it i'll say delete and i'll show you that of course you can skip all those questions by simply typing npm in it and why and as you can guess yes of course you can come here later and then just change these values that's why it's definitely faster to just type npm in it and then the y flag so why do we need this package.json well because if i would want to install the package the local package now of course this package is going to be stored as a dependency and to show you that let's just go with npm and you know what let me clear the console first so we're going to go with npm i and then we're going to go with the package name lowdash and if you're not familiar with lodash it's just a utility library and i'm just specifically using for installation purposes there's no real reason to have low dash for our own project but it's just something pretty interesting that i would want to showcase that's why we're using lodash and we run it and notice how we installed the package and check it out now in the package.json we have dependencies property and it's an object and inside of that object we have a package by the name of lowdash now i'll show you in this video or maybe in the next one why it's so important to have this package.json but another thing that i would want to showcase once we can see that we have dependencies property if you go in your visual studio code and if you click on refresh explorer what you'll also notice is this node modules folder and in that node modules folder this is where all the dependencies are stored so if you don't have that folder already and pm creates it so in our case of course we didn't have any dependencies so when we install that first dependency npm creates that folder and this is where you'll find the dependencies now notice something interesting where for the low dash we only have one folder right so we have only one dependency but when we need to keep in mind that of course there's going to be some packages that have other dependencies and that's why i first installed lodash just to showcase that yes once you install dependency of course it is going to be in node modules but if you'll try to install a package that is bigger that uses other dependencies you'll notice something pretty cool where if i clear my terminal and if i'm gonna run npm i and then bootstrap again you can use any other package you'd want this is just to showcase how the packages work we won't use the bootstrap in this project so once i install and once i refresh check it out not only i have low dash not only i have bootstrap which i installed but since bootstrap is using jquery as well as the proper js now these are installed as dependencies and if you take a look at the dependencies property now of course we have the bootstrap as well and again the whole point of this video is to showcase why we need package.json so we need it because we need to provide information about our project and inside there a very important property is the dependencies one because in there we'll just store the dependencies which our project is using and then some packages are actually going to use more dependencies and they will be automatically installed as well in our case that was bootstrap and just to give you a taste of the package why don't we just navigate to app and i'm going to do that below the comments of course you probably would need to clean the file and as a side note the last module the http i saved in file by the name of 12 http and back in the app.js in order to start using the module in our case i guess i'm gonna go with low dash first i would need to set up the variable and common convention is calling the variable like so and we'll set it equal to require and now of course we have access to the low dash now this is the difference between node packages like for example the http or the file module or whatever and the ones that you install the external ones the external ones you always have to install first if you won't install the dependency well node won't be able to find it so in our case we did install the dependency the lowdash so now of course i can just assign it to the variable and since lowdash is utility library why don't we test out one of their methods and i'm just going to go with items and i'll create an array of arrays so items is going to be an array however the items are going to be arrays itself so two and three and then we're gonna go with four and low dash has this method the flat and deep method that effectively will just spit this back as a flat array and the way we set it up we just go with const and i'll call this new items and then since we have access to everything in this variable now i can simply go with underscore here dot and then flat and deep so flatten deep and then we'll pass in the items and now if we console log new items and if i go to my terminal and just type node app.js and by the way i need to save it so let me go back i'll say node app.js and once we run check it out in a console i can see of course the one two three four so lowdash has the method by the name of flattendeep we have access to it because we install it as dependency and now of course i can start using it now we're not gonna use bootstrap in this project because that would be too time-consuming bootstrap was just used so you can see that some dependencies will have more packages so once we install one dependency there's actually going to be more dependencies and hopefully you have a clear understanding of how you would set up package.json how we would install the package and next video i would want to showcase why having package.json is so crucial and so beneficial when we are starting to share our project with other developers awesome we have package.json we installed few dependencies and now i want to cover why having package.json is so crucial when we start sharing our project with other developers and for this example i'm going to use github as well as few basic git commands and my assumption is that since this is somewhat of a advanced course you're already familiar with git and github and you have the account if you don't please stop the video create the account and just use your favorite search engine to learn about the basics of setting up the github repository as well as basic git commands so our task is to push this up to the up and now million dollar question are we just pushing everything up including the mode modules which for the most projects is going to be somewhat big i believe i just checked in our case it was like nine megabytes but trust me it always gets way bigger than that or we would just want to send the code and you can probably already guess that since i'm implying that the size is too big that we'll have to push this up to the github without the node modules and we'll start by creating a dummy repo on a github so let me open up a new window i'm going to go with github and i'll just create a temp repo and then i'm just going to create a repo and i'm looking for these three commands essentially i would want to get that url the remote url so i know where to push it and then inside of the repo before we set it up as github repo first i would want to go with new file and we'll create a git ignored because of course what i would want is to place the node modules in a git ignore file because that way they will be ignored by my source control and i won't be pushing up this giant folder to the github because you'll see in a second that there is no need for it so we're going to go with forward slash and then node modules and if you're not familiar with git ignored it's just a file that specifies which files are going to be ignored by the source control and in our case as you can see i'm placing node modules inside there then i'll clear my console and i'll just initialize this as an empty git repo and then we'll add everything so git add git commit we'll just say first commit first commit and then i'll copy and paste those three commands in order to set up that url the remote url and once i have this in place should be able to go back to my github and there it is this is my repo now probably your next question is okay so we pushed it up to the github but i can clearly see that in my app.js well technically i'm using the load as dependency right but we didn't push up the node modules folder so how the person who is going to get this repo will be able to run the code in the app.js since there's no node modules and you told us previously that we can only run it if the dependency is there well let's check it out i'm going to go with clone option so i'll just get the url i'll navigate back here and i'll do that in messed up again it doesn't really matter we're just going to go with desktop and then git clone now i copy and paste the url i'll open up a new instance of my text error copy and paste and this is where the magic happens if we have package json we simply need to run npm install and what is going to happen the npm will check for dependencies that we have in the package.json and automatically set up that node modules folder so if i go here first of all i can see that there has been some changes that is already good news that just means that i have my node modules and if i refresh check it out so now of course i have my node modules folder and if you have been using react applications you're probably already familiar with this one where again when you are setting up the code you're not sharing the node modules folder and i can showcase that by taking a look at my react projects and that's not what i wanted i didn't want to look at my awesome picture what i wanted is react and then let's go with project and you'll see that in that repo we have bunch and bunch of folders and each folder has two more folders final and setup and now check it out none of them have the node models because imagine the size of this sucker if i would push for every project for every folder the node modules instead i have package json so when you get the repo when you clone the repo or download or whatever then of course you get the package json and in here these are the dependencies and you just run npm install and they are being installed okay hopefully it is clear that why it is so crucial to have the package.json because we can just share the code without dragging the massive node modules folder with us we can simply just provide what packages our project is using and then once we get the repo then we just run npm install that is the command and then npm will install all the packages that are in the dependencies awesome we're familiar with npm we're familiar with package.json now let's finally install the dependency that we'll use for the remainder of the course and that is no other than the node one and of course if you want to get more info you can visit the npm and you can search for the package but as far as the general setup is just to watch our files and then restart our app for us so that way we don't have to each and every time type node and then whatever the file name and we can install it as a simple dependency that is definitely an option but since i also would want to cover depth dependencies we'll install that as a depth dependency and the command for dev dependencies is following where we go with npm and then i or install whatever and then we go with nodemon so that is the package name and then you can either do hyphen d so that just signals that that is a that dependency or you'll see this save and dev so again whichever method you choose that is really up to you but just remember that both of them will save it as a dev dependency so let's install it and then i'll talk about it why we would want to set up as a div dependency and the reason for that is because if we think about it do we really need nodemon in production and the answer is no when we push it up to digitalocean or heroku or whatever we'll of course use something more serious than nodemon to restart our application pm2 comes to mind but while we're developing yeah that is an option so in this case we'll add right away nodemon to the dev dependencies now what else what kind of packages we would add to dev dependencies for example testing packages for example linting for example formatting and that sort of thing again nothing stops you from jamming this in dependencies but if you think about it it makes way more sense if we add this as dev dependency so we use it while we are creating the app but then once it's in production then we just share the dependencies that actually the app is using not the ones that we used while we developed the app hopefully that is clear and once we have the package we're almost there now we just need to understand how the scripts work in a package.json and at the moment as you can see we have the test one we won't use that one and inside of the script object we just set up the commands and as a side note we can set up the command right now even without the node mod for example i could go with start and that command will be equal to npm and or i'm sorry node and then for example app.js so that is my command and once i save my package.json instead of running this node app.js i can simply run npm and start and there it is as you can see same functionality i run app.js and i get back the array as well as the hello world again we still exit the application so it's not like we're out of the woods but i'm just showcasing that yes we can set up the commands and then in the command we just provide a value and in this case of course it is node and app.js now for some commands you can simply type npm start as you can see but for some of them you'll have to provide the full value and that is going to be npm run and nor to showcase that i'm going to go with dev and that one will be equal and here we're gonna go with a node mod and then app.js so instead of running node like we're doing in the start now i'm setting up a dev command and in order to run this one i'll have to go with run and then whatever here's the command name again some of them you'll be able to use the shortcut where you go with start and some of them you'll have to go the full route with npm run and then whatever is the command and as a side note yes you can still run npm run start and this is also going to invoke the command but in our case we have dev and in here i have nodemon and then app js so let's try it out let's say first the package json and you should notice something pretty cool where if i go with npm run and dev now i'm spinning up the node one and it tells me that nodemon is watching my application and since i know that of course we can test it out where i'm gonna go with console.log and then instead of the hello world which i have after new items i'm gonna go with hello people and you should see something interesting where once i change the text yep nodemon restarts my app and now of course my value is hello people awesome so now i don't have to type every time the node and then whatever file name nodemon automatically just restarts my app and i simply set it up as a script now if you want to change this around if you don't want to run npm around dev you can simply say nodemon and then app.js and just remove the dev1 completely and a side note again if you have worked with react project you are familiar with the setup because for react again we run npm start and then there's a value that spins up the whole react dev server where we can see our application not bad not bad well we're still on a roll let's cover how we can uninstall the package as well and as a side note if you want to stop the nodemon just press again ctrl and c and notice how we're of course stopping the nodemon and again if we want to spin up we'll just go with npm start and as far as uninstalling the package we have the command for that and the name is uninstall so i'll stop the nodemon and in the terminal i'll type npm uninstall and then of course the package name which in my case is going to be a bootstrap now this is one of the approaches how we can do that and there's also a nuclear approach now why i'm calling this a nuclear approach because that way we remove the whole node modules folder and don't worry once you run the npm install then of course you set everything back up from the scratch as well as you would remove this package like json and don't worry i will cover the package.json file a bit later and the way that is going to look like well we can first clear the terminal i'll install the bootstrap from the scratch again so say bootstrap here and by the way probably need to add npm i and now again as you can see i have it as my dependency and then like i said the nuclear approach is removing the node modules yep and then removing the package log and then just running npm install now of course in the package.json if i want to remove the bootstrap for example in this case i can simply remove it from my dependencies so i just remove it in the package.json then clear everything and then we go with npm and then install and now we'll get from the scratch the node modules since we're the ones who removed it and also we'll get that package hyphen lock json now i'm showing you that nuclear approach because if you have used gatsby you know that cats be somewhat notorious for sometimes just being a little bit annoying where you do need to remove the cache folder you do need to remove the node modules as well as package lock and then once you start up everything from scratch then as a magic the gatsby app starts working and check it out if we take a look at the node modules now yes there's a bunch of modules that nodemon is using right but there's no bootstrap and i can clearly see that because there's nothing under the letter of b so we can clearly see that we removed bootstrap from our dependencies all right and now let's take a look at how we can install package globally and what would be some of the use cases and first let's start with command let's jog our memory command was npm install and then dash g and the package name and in mac they might ask you for permissions so you'll have to start with sudo and then again same spiel npm install blah blah blah and first i want to showcase that i haven't installed nodemon globally and the easiest way for me to showcase that is by running nodemon and app js so we'll try to install nodeman package globally why well because then i can use nodemon in any of my projects at the moment i have it as a local package and of course i can spin it up by running npm start but let's imagine scenario where i have i don't know 20 nodal applications and i'm constantly working on node applications so to make my life easier i will install node 1 globally and then i won't get this error because at the moment you can see command not found normal all right so how do we do that well we can install it in our terminal or we can do it in the integrated thermal it doesn't really matter when it comes to global packages you can install it from anywhere so in my case i'm just going to navigate back to my terminal just so you don't think that i'm cheating and i'll zoom in and we'll simply run and by the way i need to start with sudo and then npm install and hyphen g and of course we're looking for nodemon so now of course i'm prompted to enter my password and once i enter my password of course i'm going to install nodemon globally and now in any of my projects i can simply go with command of nodemon and then whatever is the file name now to show you some of the use cases if you work with gatsby you know that they have the global gatsby cli tool and that was one of the reasons why you installed something globally is because well you used one of the frameworks for example react or gatsby in this case and then of course in order to set up the gatsby project or react project you needed to install this globally now things have changed though with arrival of npx and i'll talk about the npx at the end of the video but notice if you navigate to your react docs and if you look for create react app which again was something that you needed to install globally now they suggest this npx route where essentially you go with npx and then again whatever is the command name for example for create react app that would be create react app for strappy the headless cms that would be create strappy app and hopefully you get the gist where for every resource that of course would be different and with that command you don't have to install that tool globally for example again in our case we're installing nodemon but normally prior to npx you would install this create react app globally and then you can spin up those react projects now i'm going to go back to my terminal as you can see i was successful so what's going to happen if i go back to my project and if i run nodemon and app.js since i have installed that package globally there it is i spin up my app.js and if you don't believe me i can change it back to hello world and i have no issues hello world and there it is now of course i have hello world e in the console so hopefully it is clear that yes we can install packages globally and yes one of the biggest use cases was working with some type of front-end library but with an arrival of npx things have shifted where now those libraries suggest using the npx route instead as far as my personal preference since i'm recording a lot of courses and since some of the global packages usually introduce some kind of bugs to the students now not for all the students but there's always this one student who just has a lot of issues with the global package personally i avoid them as much as possible so i always either use the mpx or i just set it up as a local dependency again it's not a rule you can do whatever you would want but i'm just telling you what is my preferred option as far as what is npx it stands for execute and official name is the package runner it is a feature that was introduced in npm 5.2 and again the main idea is following where you can run that cli tool for example in this case create react app without installing these globally so as long as you have npm with a version of 5.2 or greater instead of doing this whole spiel of setting up the cli tool globally you just go with npx and then whatever here is the tool name and of course the last one is the folder name as far as the package log json why do we need it well if we take a look at our dependencies we can see that they have versions and if you remember some of the dependencies have dependencies on their own and of course we need to keep in mind that those dependencies have versions as well and for example the person who gets your project you probably want them to have the same exact setup because keep in mind as these versions change well so does some of the functionality correct so for example you set up to your whole project you use some kind of dependency that uses some other package and that version changes not for example for the bootstrap but for the jquery and then pretty much your project is obsolete meaning it might get some bugs because the version of the jquery changed so that's why you have this package.json and in there you have those specific versions for all the packages not only for dependencies but also for the packages that the dependency is using now as far as this version we have three values and you can think of it as a contract between us the people who are using the package and the person who is creating and first number is a major change so when this changes that means that there are some breaking changes now the second one is a minor one so that means that it is backward compatible so for example if this changes to 18 i shouldn't expect any breaking changes and the last one is just a patch for the bug fix so that's also something to keep in mind when you decide to publish your own package that of course that's why we have here this version now lastly i would just want to mention that if you're interested in more info about the package.json i would suggest this resource so i simply went with package.json then keep on scrolling keep on scrolling and you're looking for i guess this blog post right so the name is the basics of package.json and in here you literally find everything explained to the smallest detail whether that is a name version and rest of the fields that you can find in a package.json beautiful we now know how to utilize npm and for starters as a result for the remainder of the course instead of frantically typing node.js in a terminal we'll simply spin up nodemon and it will watch for the changes and restart the app for us now what before we move on to creating servers with express.js there are a few important node topics i would like to cover first and those topics are following event loop async patterns in node.js events emitter and streams in node.js while these topics are extremely important please keep in mind that our goal is to only understand the general ideas behind these concepts and i only introduce them so you have an overall understanding of how things work in node.js before we build our first node.js app if you're not satisfied with my explanations or simply want to do more research by yourself just type any of these terms in your favorite search engine and i can guarantee you'll find plenty of useful resources within a matter of seconds like blog posts youtube videos and conference talks with that said it's my strong opinion that it might be easier to understand those concepts more deeply so not just a general understanding but understanding them more deeply once you have one or few working node apps under your developer's belt let me also mention that in order not to waste your time with time consuming setup in few upcoming videos i will run some pre-built code let me be very clear though i'm only going to do that in a few videos and for the remainder of the course we will type out everything together all right and let's kick things off by discussing the event loop now event loop in node.js is one of those topics where i could spend the entire course discussing it and it still wouldn't be enough so let's try to avoid that and instead just understand the journal concepts while there are tons of useful event loop explanations out there the one that i probably like the most is this one the event loop is what allows node.js to perform non-blocking i o so input and output operations despite the fact that javascript is single threaded by offloading operations to the system kernel whenever possible and as you can see i'm reading straight from the node docs now don't beat yourself up if this sounds like a lot of gibberish there's a reason why one can dedicate the entire course just for event loop it is a pretty complex topic but one word i do want you to remember is this offloading and you'll see why in a second also don't worry i have prepared more examples as well as some slides to get my point across but just in case you're not happy with my examples or you just want to explore the note event loop in greater detail here are a few external resources i find particularly useful when it comes to blog posts just go to your favorite search engine and type node.js event loop and the one that i find really useful is this one and the resource is nodejs and not.org but it is dot dev and then follow the link and here they cover event loop in great detail with a lot of cool examples and pictures and slides and all that good stuff and when it comes to videos i would suggest going to youtube and then just type event loop and the first video that's going to pop up is going to be the event loop bot in browser javascript and i'll talk about it in a second and the nodejs specific event loop video is this one i believe it's 15 minutes long and you can see the name over here so this is a very very useful video where the speaker covers a lot of useful details about node.js loop in great detail and the reason why i'm suggesting the first one as well well what is the language that we use in node that of course is javascript right and even though there's some differences between the event loop the one that we use in the browser and the one that is in the node.js if you understand the concepts behind the event loop that we use in a browser trust me you're already halfway there to understanding how the no js event loop works since it's such an important topic like promised i have prepared some of my own resources as well we'll start with the slides and move on to the closed examples in next video as a side note i made all the course slides available on course api.com again their website name is coors api.com and once you click on the slides link you'll see all the slides and i would want to start our discussion by taking a look at what it means that javascript is synchronous and single threaded and effectively it's just a fancy way of saying that just repeat everything line by line so for example if i have console log with first task then i have a for loop that takes some time in this case two seconds but that could be 10 seconds that could be 20 or whatever and then i have another console log of next task javascript will just start reading everything and it will read it line by line and if this takes a long time it will only run the next test once it's done performing this time consuming one so hopefully that is clear that javascript just reads everything line by line and now let's take a look at our second slide and in here we can see the solution if we would want to offload something to the browser so when we're building browser javascript apps we have this option of offloading to the browser now of course it doesn't mean that we can offload the for loop that's not going to work this effectively is still going to be the blocking code but browser nicely provides the api where we can offload those tasks to the browser and only when the task is done then we execute the callback and probably the example we have done the most is the fetch essentially when we make the network request but we can also do that for example with a set timeout so i still have console.log with first task but then even though my set timeout function has the second argument of zero so essentially i have set timeout function i provide the callback function that's going to be executed in certain amount of time even if this is zero meaning you would expect this one to run right away it only runs after the next task so once javascript is done executing the immediate code only then it executes the callback so in this case we have the set timeout the api that is provided from the browser and we just said that we would want to execute that e in zero seconds so effectively there is no wait time however javascript will first execute this code and only then will execute the callback so that way we can offload those time consuming operations to the browser again it doesn't mean that we can offload for loops it means that browser does provide some apis where we don't have to write the blocking code now let me be very clear though when i say we cannot offload for loops what i mean is that we can still write blocking code in javascript but the browser does provide some nice apis where we can offload those time consuming tasks and that brings us to our main friend the nodejs event loop again before i go over the example let me stress something event loop is somewhat complex and this is just to give you a general understanding so let's imagine this scenario i have an app and just like any cool app i have subscribers or users or however you would want to call them and in this case since my app is so so popular i have eight of them and what do the users do well they're probably being annoying and they're requesting something from the application and as the requests are coming in the event loop is responsible for avoiding this type of scenario so let's imagine this i have all these users the requests are coming in but larry the little decides that in his request there's going to be some kind of time consuming i don't know database crawl or something like that so effectively he's requesting something and behind the scenes in my code that means that i need to perform something that takes a long time so in this case the event loop just registers the callback so it registers what needs to be done when the task is complete because if the event loop wouldn't do that then we would have this scenario where the requests are coming in and because larry is requesting something that takes a long time the rest of the users would have to wait and essentially it's not that the actual operation takes a long time it's just the fact that we're wasting our time on waiting for that operation to be done and only then we can serve the other users but what the event loop does it registers the callback and only when the operation is complete it executes it now keep in mind that again we're not executing this right away when we can effectively it's the same scenario where we run our immediate code first and only then when we have the time we execute the callback so for example in this scenario if i would have hundred console logs after the next task i would run them first and only then the second task would appear here regardless of what is the time set in here because again we're running our immediate tasks first and only then we run the callbacks so the same thing happens here where the requests are coming in let's say that the operation is complete we first registered the callback operation is complete and instead of executing that callback right away it effectively gets put at the end of the line and then when there is no immediate code to run then we execute the callback hopefully that is clear event loop is our best friend because with the help of event loop we can offload some time consuming operations and effectively just keep all our users happy all right and once we have looked at the event loop in theory to hammer this home let's also take a look at some code examples where we can see event loop in action as a side note all code examples are located in the event loop example directory so if you need to take a look just grab the repo and you can find it there and you should be familiar with our first example since it's a async version of read file method so we import read file from the fs module and then we have console.log started our task first then we have read file method where we pass the path we pass the encoding and then of course we have the callback and then in the callback i cancel logged first result and then of course i have completed the first task and then right after the read file i have starting next task and something really interesting in a console i can see that we first cancel logged started the first task then i right away have starting the next task and then of course once i'm done once i get back my result then of course i have hello this is first text file and of course completed first task and again the reason why is this happening because read file is a synchronous and we already know that event loop will offload this in this case to a file system so we start reading the file notice like okay run this line of code then offload this one and only when i get back to the result then run the callback so when the file system responds with error or the data then we invoke this one all right so we offload this task and we just keep on reading the code that's why we have started the first task starting the next one so right away go to the next test and this one this asynchronous one well we're just offloading and then once the response comes back whether it's an error whether it's a success only then we invoke the callback hopefully that is clear now as far as this comment i only added this one because we need to keep in mind that of course i'm just grabbing this code from the file but the file is sitting in the folder so if you were to run nodemon and then directly the filename which is of course going to be in the event loop the path won't match so this path only matches because of course i have app.js but if you'll try to run this code directly in this file that's why it's not going to match and you need to go one level up now my assumption is that you're running it the same as me and you're running that with npm start that's why i kept the path matching to the one in the app.js now our next example so let me clear my app.js i can close the read file as well as package.json and then the next one is set timeout so select here everything and copy and paste in my fgs i'll restart and then i have two console logs and the third one is e in a set timeout and this is pretty typical example for javascript loop as well if you have taken javascript courses which again i assume you have since you're watching the note one you probably remember this example where i got you here is following yeah i have the console log first and i have the second and third and you think that since set timeout is set to zero so since we're saying yeah call this callback function but actually wait only zero seconds you'd think that the order would be first second and third right well wrong because we have first third and second why well because set timeout is asynchronous correct and what happens with asynchronous well they get offloaded so in this case we run first third and then the second because this one gets offloaded again this one goes to the back of the line and only when we're done with our immediate code pretty much with our synchronous code only then we invoke that callback all right now i also added these comments here where i have started operating system process and then completed and exited the operating system process and the reason why i'm showing you that because in next two examples we'll do something a little bit different so now i would want to go to set interval and by the way it's going to be a bit clearer if we run here node and then app.js so let me stop this and i'll go with node and objects and you'll notice that we started the operating system process and then the moment we're done with the code that's it we exit now if we'll take a look at the set interval you'll notice something really interesting where if i go with node and app.js notice something interesting and by the way of course i didn't copy and paste so go to the third example and then just remove all this code and copy and paste so that's my third example and in here i have the set interval now again yes we'll have to run few times node app.js and now check it out so what i see here is i will run first so that's my console log and then i have the set interval and notice how we're not exiting the process here so we start the process similarly to the second example but if in the second example we actually exited because we completed all our tasks in this case we're not doing that why well because set interval is asynchronous now the difference between the set timeout and set interval is the fact that set interval runs in those increments in this case of course it is those two seconds so every two seconds the event loop is just gonna invoke that callback now that's why we're not exiting that's why we're still in the process and we can only exit the process if we kill it so that would be control and c or there's some unexpected error otherwise it will always stay alive now again keep in mind one thing where notice i will run first was first why well because again this is asynchronous and i know i've said this before 20 000 times but again this is probably the core building block of no the fact that every time we have some asynchronous action it's just going to be offloaded and then when it's time we invoke the callback and our last example is a server and again i just wanted to showcase how the process stays alive so i'll take all the code and copy and paste in app.js now i'll stop this one so stop the process and then we'll clear the console and again just to showcase how the process stays live i'm going to go with node and app.js and i'm doing that so you're not confused with nodemon and then check it out so we have server listening on port 5000 and then every time the request comes in well we invoke this callback and in our callback we're simply cancel logging request event and then we send back the hello world so now if i were to go to a localhost 5000 there it is i have the response of hello world and in a console i'll see this request event and check it out how again this process stays alive why well because listen is asynchronous and the moment we set it up now event loop is just waiting for those requests to come in and then once they come in then of course we run our callback now please don't confuse this callback with what we're responding our request i went so this callback is just when we're setting up the server because in here we can have the success over there so in our case as you can see everything went great we have server listening on port 5000 but of course there also might be an error and this one of course just responds to that request event but the whole point is with server.listen we just say hey event loop just keep listening for those incoming requests and the moments show up then respond to them appropriately hopefully it is clear and of course we can move on to our next topic all right and up next i want to talk about asynchronous patterns in node.js so if we remember when we were setting up the file system module we covered how we have two flavors we have the synchronous one and the asynchronous one and while asynchronous one is great since we're not blocking the event loop the problem is that if we're using this callback approach well it gets messy pretty quickly right because we're nesting one callback inside of the other one so now in the following videos i would want to show you the alternative that we'll use throughout the course and why in my opinion it is much cleaner syntax and that's why of course we'll use it and first what i would want is just to kill everything here and i'll start with the nodemon since i'm done showing you the event loop and we're just going to go with npm start right that was the proper one and now i'll delete everything that i currently have not here sorry so i'll leave this one the async one i would want to remove everything in the app.js and now i just want to quickly show you the code that would block that event loop again this is going to be the video where if you don't want to code along you don't have to you can just sit back and relax and effectively you'll be in good shape and again we'll set up the server like i mentioned before already 20 000 times don't worry about specific commands we have rest of the course where we'll be building servers so trust me you'll get sick of it so go with http and require and of course we're looking for http module and then remember the methods create server and listen so we go with const and we create the server that is http and create server we pass in callback a callback takes two objects request object and response object so again essentially request object is what is coming in and response object just represents what we're sending out what essentially we are responding and then i would want to listen on a port again so i run server.listen and then i'll pass in the port of 5000 and then of course we have that callback once the server is ready and in here we can just go with console.log and we'll simply say server is listening on port 5000 server is is listening or just listening listening on port and then of course in my case port is 5000 let's set that up so we should have this listening on port 5000 and then of course in my callback function i would want to check 40 urls because i want to show you how even if we try to get a different resource we're still blocked by other user if he or she is requesting some kind of resource where we have the blocking code and don't worry if this sounds like gibberish you'll see what i mean in a second so remember on the request object we could check for the url so effectively you could check what is the resource that the user is requesting so for example home page would be forward slash and then the about page would be forward slash and about and that is sitting in the property by the name of request and url so request is the object and then url is the property so again we'll do a quick and dirty way we'll just say request url is equal to a forward slash that means it's a homepage and then we just need to go with a res.end and then we'll say home page again later we'll have way more sophisticated approach but for now this will do and then we're checking for the about page okay awesome so this is going to be an about page and then if there's a page that doesn't match any of the resources then of course i'll just send back i don't know error page i'm not going to set up the whole link nothing like that all right we save it and then this should send back about page awesome and then of course in home page i can just respond with the homepage so life is beautiful users can come here and as a side note multiple users i'm representing with these tabs so imagine these are my users and life is beautiful we are requesting resources and we're just going on about our day now the problem is going to be if i go to about and if i set up some kind of blocking code now what would be a blocking code well that could be a nested for loop so i'm just going to go with blocking code and then i'll add some exclamation points and let's simply set up a for loop let's say i is equal to zero and then let's say i is less than thousand and yep i plus plus so every iteration will increase by one however i'll set it up as a nested portal so copy and paste and i'll just change these values to j so j here and j here and then let's just cancel log and we'll say j and i again doesn't really matter what we type there just say i and j now known dialogue question what do you think is gonna happen so if the user navigates to about i mean we can kind of see that this will take some time right now you would expect though that only the user who navigates here gets blocked and you'd be wrong because we'll also block the other suckers who are just trying to get to the homepage so let me navigate here and check this out so i run this one and notice how we're loading now the same thing happens here now and here okay and only when we're done here then these two can get the resource again now of course if i go to my project i can see that in the console i have all these values right because i have this blocking code i have the synchronous code that just takes a long time and this is just a representation of why we prefer this asynchronous now yes at the moment this is messy and don't worry in the next videos we'll fix it but this hopefully gives you an idea why you should always strive setting up your code asynchronously because what we've learned in the previous videos if we do that then those tasks are offloaded and then only when the data is back only when it's ready then we invoke it and that way we're not blocking the other users hopefully it is clear and now of course let's take a look at some other patterns we can use so we still get the benefits so we're not blocking that event loop but we also have a cleaner code where we don't have this nested callback mess all right and once we have covered why it's so important to use the asynchronous approach now of course let's clean up our f a a sync so instead of using these nested callbacks let's see a nicer pattern and as i say note if you want to see the code that we wrote in a previous video and the one we are about to write then the files are located in two async patterns folder so i'll close everything for now and then back in app.js i can remove it like i said if you want to access that code it is sitting in the two async patterns folder and we'll simply start by recreating the read file setup where i'm gonna go with const and i'm right away accessing that from the file system module and i'll set it equal to require of course and then file system all right that's awesome we know that it is asynchronous so we need to set it up with three parameters we go with read file and then we would want to pass in path first so again since i'm in app.js i'm going to be looking for the content and then forward slash and then first txt the file we already created before then we have encoding so comma and then again we're going to go with utf-8 and then last one is going to be that callback where the first value is the error and then the second one is the data that we're getting back okay awesome so once the file system responds then of course we invoke this callback and inside of that callback we have our logic so if there's going to be an error for time being i will just return like so and then if i have the data i'll set it up as else so say here console log and data of course and we shouldn't be surprised if we've seen a console hello this is a first text file because we already covered the setup right so we're passing the path we pass in the encoding and then we set up the callback now the problem starts if we would want to perform multiple actions if i want to read two files and then for example write one correct so what would be a better solution well a better solution would be turning this into a promise and then eventually we'll set up async await now please keep in mind that the only reason why i will type out the promise stuff is because i would want you to understand what is happening behind the scenes but don't worry throughout the course we'll just stick with a sync and a weight syntax and essentially you won't have to worry about what is happening behind the scenes but the first example yes i want you to understand everything in detail so what we could do is create a new function and we can just say const and then i'll call this get text now this get text will take a path since i want to read two files and then eventually write one as well just like we did here and of course the goal here is to showcase how we can make the code in the file fs async at least that's how i called my file much cleaner and more readable so again we pass in the path and then what i would want to return from this function is a promise so we go with return new promise and then in the promise object we need to pass in is another callback function so we pass in the callback function and in here we pass in two more functions one for resolve and then one for reject and then once i have set up both of these parameters now of course what i would want is to move the read file and place it inside of the promised one okay so once we place it here first of all notice here how i'm passing in the path so of course i can change this one around so i can say path and then the encoding stays the same as well as the callback however inside of the callback once i have access to resolve and reject what i could simply say that if there is an error i will spit back the error so say reject an error and if everything goes great now of course let's go with resolve and then we'll pass in the data and once we have this setup what's really cool that now i can invoke get text and this is going to return a promise and then of course we can chain that then and catch so below the get text i can go with get text and of course we're looking for the path so we still would need to use dot and then forward slash and then content of course and first txt so that's the path and then like i said we are returning a promise so we can chain that then and of course here i can have the result and i'll just cancel log it for now or result and then i can also chain that catch and here i'm passing in the error so again we can't log it and we simply would want to see the error i save it and beautiful again in a console i have hello this is first text file so i know that it worked and also if i change the path so if i make my path incorrect we should see in the console the error where of course node cannot find file so if that works now of course we can take a look at how we can make it even cleaner by setting up async 08 and once we have our initial setup once we have turned this into a promise technically we're not out of the woods because if i would want to perform again two file reads and then eventually write the file as well and if i would want to do all of that asynchronously it's still going to be paying just by using the promises so what would be a solution well since we're returning a promise if i use async await i can wait till promise is settled and then decide what i would want to do and the way we set that one up is by creating a new function now please keep one thing in mind where eventually throughout the course those functions that i'm about to set up are going to be provided to us so we'll just attach that async to the callback functions that already provided us by the libraries okay but in this example i'll have to create one from the scratch and again the whole point here is because i would want to create a function a start function that i'm going to set up as a synchronous function and i would want to attach a weight so i would only respond once the promise is settled so in here i go const start and that's my function but i need to set it up right away as async because i would want to use my await keyword correct and then we simply go with const and i know that of course i'm looking for the first file and i'll just say first and that one is equal to get text and basically i want to pass in the same thing here now i do need to place this one in quotation marks so my bad i messed it up a little bit okay i passed it in and that should do it now of course what i'm missing here is a weight so i had this await and now only once the promise is resolved then i'll get my response so what i could do here is just comment these two or you know what this one i cannot comment out yet don't worry we will eventually this one i can comment out and then maybe move this below okay so you don't think that i'm running this code and since i have my function now of course i would need to invoke it so invoke start and check it out now of course i don't have the error which is a good sign i guess and then we'll simply go with log and none first and notice the difference where previously when we were setting up the callbacks we had to nest everything now i'm waiting for this promise to be resolved and only once it's resolved then of course i can do something with the value now every time we have this async await approach what we would want is to wrap this e in the try catch block so if something goes wrong then we have at least a little bit of control over it so i'll set up try catch block and then i'll set up my first await and eventually we'll add here more and then in the error i'll simply go with console.log and we'll console log the error and let's just save that one so now we have nice try and catch block and by the way sorry i deleted it we'll still take a look at the first one and then if we change the path then of course we'll get an error okay so that's good now i have my start function it is the synchronous i'm waiting for the promises to resolve they're all wrapped in try catch block so what's next well if you remember in here what were the actions that we were doing well we read two files correct and then we wrote one okay so let's try that one with this new approach where essentially i have first so just copy and paste and then i'll look for the second file remember we should have that in the content so this is going to be the second one second over here and then i would want to write the file now of course you could say well the problem here is going to be that i'll have to write a new wrapping function to set it up as a promise because yes we can of course read the file but functionality for the write file again we would need to wrap it don't worry there's a way how we can get this actually out of the node first i just want to showcase how much cleaner this already is where i can just wait for first second like so and now notice in the console hello this is the first text and hello this is the second file again i fully understand that you're looking at this wrapper function and you're like well this definitely doesn't look that much cleaner than this one don't worry there's a way for us to get those functions in a way that they're already returning a promise what i would want you to focus on is this code what i would want you to understand that this definitely is much cleaner than what we have here we read the file and then we set up another nested callback and another nested callback and hopefully you get the gist waiting for these promises to resolve is definitely a cleaner and more readable approach all right so this works we have our start function it is asynchronous we're waiting for prompts to resolve and we can see that it is already much cleaner how we can set up this code without the wrapping function well what's really cool that in node there is a module by the name of util and we just go here const and we'll assign it to a variable and we'll just be looking for require of course since we would want to import the module and again the name is util and then instead of this module we have a method by the name of promisify and with the use of this function we can take our read file which of course was looking for the callback and turn it into the function that returns a promise and again this is over simplified version what is happening there but hopefully you understand that as a result we'll get again this promise back now the way we'll set that up of course we have read file here already so i cannot use the same name that's why i'll go with read file and we'll call this promise and that one is equal to util that is of course my module dot and then notice the function promisify and then we pass in that read file function so now i have my promise one so now what i could do is first of all comment this out and move it down again so it stays for your reference but it doesn't compromise my view and of course now i have the error because well get text is not defined that's fine don't worry and i'll copy and paste and since i also want to write a new file i will get from the file system one the right file function and then i'll do the same thing where in this case it's going to be called write file promise and then we pass in write file and of course now instead of calling get text what i'm gonna do is go with right file or i'm sorry in this case we're going for read file promise and then keep in mind one thing where this is not a get text one so we're still looking for the path as well as the encoding that's well copy and paste and then second argument we pass in is the encoding and again our functionality shouldn't change where i should see in console the results from the first txt now of course i want to do the same thing with the second one so have read file promise second txt again we have to pass in the encoding otherwise we'll get the buffer back so copy this and paste and again if we cancel log it there it is we have hello this is first text file and this is the second one and since in the line 4 we passed in write file into promisify of course what we could also do is right away write the file so i can go with await and i'm simply not assigning this to a variable because well i'm getting back on the finder as far as data and i'm just going to go with await write file promise and the same spiel we pass in first the path and in this case of course if the file is not there node will create one and the name will be result and i'll just call this mine grenade and then txt and then the second one is data so for that one i'll set up my template string and i'll just say this is awesome awesome and then let's set up the colon and then we'll access both first as well as the second one so we'll interpolate both of them second and then once we save if we take a look at the content there it is now we have the mind grenade one correct now there's probably one where i was testing yep there's one where i was testing so i'll remove this one but if i take a look at dtxd1 then of course i'll have this is awesome hello this is first text file and then i have the second one now what's even more cool that technically we can even skip this part as well again i'll leave this one for your reference but if you go to require and then you require of course file system module but if you add dot promises what do you think is going to return well effectively the same thing so now of course i just need to change the name from read file promise and write file promise back to read file and write file since those are the two functions that i'm importing and that will right away return promises and again we save and remember that by default we're just overwriting stuff so if i were to go and add a third argument my options one and if i'm just going to say flag and i'll set it equal to upend once we save well now we have this is awesome repeat it one more time again just to showcase that our functionality still works i fully understand that there was a little detour where we created our own wrapper function and then we covered how we would consume promises but hopefully this helps you understand that this approach is definitely way better so it is more readable it is more easier to wrap your head around and that's why for the remainder of the course we'll stick with this one again some things will be provided to us by default so libraries will provide the functions that return promises will right away have the callback functions that we'll just set up as async and hopefully you get the gist so a lot of things will be given to us but the core functionality won't change where instead of using callbacks and nesting them inside of the other callbacks and nesting more and more and more we'll set up everything with async await because the syntax is cleaner and way easier to read excellent once we have covered async patterns we're going to use throughout the course now let's talk about events in node.js when working on browser javascript apps a big part of our work is to handle events for example user clicks a button and of course in our program we handle that user hovers over the link and again same deal in our program we are handling that and hopefully you get the gist essentially as our program executes at least in part it is controlled by events of course depending on a program but it's safe to say that in browser app those events are mostly external now that style of programming is actually called event driven programming and effectively it's just that a style in which the flow of the program is at least in part determined by the events that occur as the program executes now it's easier to imagine that of course when you have a gui right the graphical interface just like the button and links example i just mentioned but what about server side is it also possible and of course the answer is yes in fact event driven programming is used heavily in node.js and in the following videos we'll see some of the examples of it and basically the idea is following we listen for specific events and register functions that will execute in response to those events so once our event takes place callback function fires just like in our imaginary button example now before we continue let me stress something our first examples are going to be basic and even somewhat silly but don't let that fool you many built-in modules in node.js do use events under the hood and therefore making events and event driven programming a big part of nodejs all right and once we have covered general concepts behind events as well as event-driven programming now let's set up our own events in node and the way we do that we come up with a variable and typically this name is event emitter because what we're getting back is the class and we require the events module so require events module and we assign it to a variable which essentially is a class and again a common practice is calling this event emitter and at this point you have two options if you want to create something custom you'll need to extend the class or if you simply want to emit an event as well as listen for it then you can just create the instance so go with the second route we'll go with const and then whatever name you would want in my case i'm just going to call this custom emitter like so and i'll assign it to new emitter so event emitter or however you call this variable and we just need to invoke it so now we have the instance of our class so essentially we have the object now there are many methods in this object however two that we're interested the most are on and emit so on we'll listen for specific amend and then emit of course will emit that event and the way we set it up we go with custom mirror or whatever name you used and then we go with on and at the very basic setup in the on method we just pass in the string where we say the name of the event now in my case i'll name my one response and then of course once i have subscribed to it i also would want to pass in the callback function so essentially when this event takes place well then i would want to do something and in my case i'll just go with console.log and we'll simply say data received or i'll place this one in the template strings and you'll see in a second why so we'll go with data received and then eventually there's going to be some more data and of course once we have subscribed to this specific event now i would want to admit it and the way we do that we just go with custom emitter and of course the method is surprise surprise emit and of course at this point these strings need to match so if i'm emitting the response event and just say here response and what you'll see in the console is wherever you have in callback so of course in my case i have console log data received and then once i run it i have data received in console so that's the most basic setup when it comes to events again we create an instance from the class that we get back from the events module and then we have two methods we have on method as well as the emit method and then in the on method we pass in the string so that's going to be the name of the event as well as the callback function so once this event takes place then of course we would want to do something and in our case we'll just console.log data received and then once we have subscribed to this event then of course we need to emit it and the way we do that we just go with whatever the name is in my case custom emitter then emit method and then we pass in the same string that we're listening for in our case of course response and then the moment we do that we of course have whatever is in the callback function which in of course of course is just a simple log data received all right and once we have covered the basic setup now let me show you some things that i would want you to be aware of first we can have as many methods we would want so for example we have the same event we have here response correct and we are omitting it so nothing stops me here just copy and paste and listen for the same event which of course in our case is this response and then do some other logic in my callback again in my case it's just going to be simple different kinds of log so i'm going to say some other logic here and i'm not going to copy and paste the same function 20 000 times just to prove my point but hopefully understand that yes we can emit our event and then yes also we can have as many functions we would want here that our listening for that event and do some other logic so that's point number one point number two that i would like to make is the fact that this order matters so we first listen for event and then we emit it so for example if i will place my emit above the second function or above both of the functions which you'll notice that i have nothing in a console why well because i first emit the event and only then i listen for it as you can see that doesn't make sense so first we would want to listen for the event and only then we would admit it so in this case notice i don't have this some other logic goes in here because i listen for response and then i right away admit the response and then again i listen for the response but i already admitted the event correct so it doesn't make sense to listen for the event once it has been already emitted so that's the point number two and then thirdly our also on a showcase that we can pass the arguments when we're omitting the event so for example i go here with my emit i pass in the name which is of course response and then i can pass in more arguments for example here i'll go john and then the id number 34. so string and a number and then in my callback function i can access those arguments as parameters just like normal functions so in this case i'll call them name and id and simply in my console.log i'll say name and the second one will be with id and then whatever is that id now i'll add here data received user and then save it and it's no surprise that in the console i see data received user john with id34 now in the second function as you can see i wasn't looking for those arguments i just don't have access to the arguments because i don't have the parameters but it's not like everything broke just because in the event i passed in the arguments and lastly i would just want to reiterate the point that even though you might not write your own events events are a core building block of node and effectively as you're building and writing out the code for your node application you are using those events at the end of the day anyway because a lot of built-in modules rely on them and as a quick side note if you'd like to see the code that we wrote in previous two lectures you can just navigate to 13 event emitter and in order to show that i'll quickly set up a server and again the code for this one you can find at 14 and then request event so copy all the contents from the file and then just copy and paste and notice something interesting where again yes we're getting the http module and remember the setup that we have used so far where we go with http create server and then we pass in this callback function and then of course this callback function will be invoked every time someone visits our server so every time the request comes in now there's another way how we can set it up by using event emitter api so we still create a server we go with http and then create server function but instead of passing in the callback function like we did previously server has the method on does that ring a bell remember our previous example we had our own instance and it had the method of on correct so the same goes for server so server has the method on and we listen for request event and when that request comes in then of course again we have this callback function that handles it so behind the scenes server emits the request event and then of course we can listen for it we can subscribe to it listen for it or respond to it however you'd want to call it and the way we do that we go with server on and then this is a specific name because of course it emits that specific name behind the scene so make sure that it is a request and then the same spiel now how do i know that well if we go to node documentation and if we look for http we keep on scrolling keep on scrolling eventually we'll hit the server and over here i can see that it has a clash okay that's a good start and that what do you see here well i see the event right and what is the event well the name is request so that's how i know that my server the instance that i create has the ability to listen for request events and if you want to dig deeper you can just click on a server you notice that it extends the net server and if we keep on digging check it out so this one extends what it extends the event emitter so hopefully that makes it clear that even though you might not be setting up events on your own a bunch of built-in modules rely heavily on this concept of events all right and up next we have streams in node.js and at its simplest streams are used to read or write sequentially basically when we have to handle and manipulate streaming data for example continuous source or a big file streams come in real handy and now there are four different types of streams we have writable used to write data sequentially then we have readable used to read data sequentially duplex used to both read and write data sequentially and also transform where data can be modified when writing or reading just like with events many built-in modules in node implement streaming interface and what's also interesting streams extend event emitters class which simply means that we can use events like data and and on streams since streams are somewhat off an advanced topic in node i'll try to keep it short and sweet mostly by showing you examples of streams and hopefully that way you get the main idea without being overwhelmed all right and once we know the theory behind the streams now let's take a look at the practical example and a very good use case is using streams when we are reading files because we need to understand one thing where when we use the sync or asynchronous approach what happens we're reading the whole file and of course in our example we were setting this equal to a variable correct but if we have a big file well first of all you're just using all that memory and second as the file size gets bigger and bigger bigger eventually the variable is not going to be good enough you will get an error that i mean the size is too big and you cannot place everything in the string so what would be a solution one solution would be read stream option and the way we'll set this up i'm going to start app.js from scratch but if you take a look at the repo you'll notice this 15 create big file so previously when we were working with files i just had some small files right so i had the first txt blah blah blah result and whatever now before we set up the read stream i would want to create a big file again this is optional you don't have to do that but in my case in order to show you how the streams work yes i'll have to set up a big file and first i'll remove it because of course i already have it since i was testing it and now i'll stop my server and of course in my case i'll run 15 the create big file js if you want to set it on your own and if you don't want to use the repo you can just get the right file sync from the fs module and then notice i have the loop where i believe i have here 10 000 and then every iteration i just write a big txt i of course i have the flag upend and then i'm just adding hello world and starting a new line so if i'll run node and then of course i'm going to go with my file name which is 15 then hyphen create big file and js like so then in the content i should have this big file and once i have my big file i'll go back to app.js and i'll use my npm start since of course i have known mine in place and then let's go with cons now i'm not going to show you how the setup would look like with file sync or the asynchronous one again hopefully you understand that the setup would be exactly the same like we have in 10 and 11 where we had the fa sync and fa async and now of course let's just go with the stream option so the method name is create read stream and we require that from the fs module like so and then we create a new variable and in my case i'll call this stream and we invoke the create read stream and the only thing by default we need to pass in is the path so of course in my case i'm going to go with content and then forward slash and since i just created that text file the big one of course i'm going to go with big txt and now remember the good old friends events well once we create this instance we actually have access to them and the ones that we're going to use is going to be data and error so we can go with stream and then on and remember the event syntax and then the event that you would want to listen for is a data and then we have our callback function and again it is a parameter so we can call whatever we would want but in my case i'm going to go result and let's just console.log the result like so and what you'll notice is that we have 64 kilobytes here that's our first console log then we have another one 464 kilobytes and the reason why i know that is because by default that's the size we're getting and then we're getting the reminder now just to prove my point i'm going to go to my folder and i'm going to look for my content and then in there if you take a look the big text file we created is 169 kilobytes so as you can see now we're reading data in chunks and by default that chunk is 64 kilobytes and every time we cancel log we see that we have 64 64 and eventually we have the remainder so instead of reading everything and placing that in the variable we're doing that in chunks and as you can see we're using the event and the event is data and in order to hammer this home why don't we take a look at the docs so first i'm going to look for my file system and then let's look for our create read stream so we go here as we can see we have this class read stream and then on this class we have these three ones we have close open and ready and as a side note we'll use this one a little bit later as well the open one so keep an eye on this one and then as far as the read stream well as you can see it is created when we go with create read stream and invoke it right so i got the create read stream that's my function i just passed in the past and i invoked it and in turn that returns the read stream right then actual read stream extends from stream.readable so right away i have these events i have close open and ready and like i said we use this open a little bit later now since it is extending from the stream check it out now of course i have the data one all right so this is a chunk of data and as you can see every time we are getting that data we can do something with it now at the moment we're just going to logging it's very simple but eventually as you can already imagine we can do way more useful things than that beautiful once we understand the basics now let's take a look at some additional info like i said by default the size of the buffer is going to be 64 kilobytes however we can also control it and the way we do that is by passing in the object when we're setting up create read stream so first argument is going to be the path which again in my case is going to be that big text file that i created using my file using my for loop and then i can pass in the options object and in there the property that you're looking for the property that controls the size of the buffer has the name of high water mark so for example if i go with 90 000 here then of course you'll see that i'll have two console logs one for 90 kilobytes and the second one will be remainder again keep in mind that our file size is 169 kilobytes that's number one number two we can right away set up the encoding as well so i go with comma and then the property name is encoding and again we'll set it up equal to utf-8 like so and then you'll see in a console of course the hello world why well because that is the content coming from the file and lastly i also would want to mention that we have the error event as well so if i go with stream and then on and we're checking for the error and as always we can do something once that error happens so that's our callback function and in this case i'll just access the error property and i'll console.log the error so i'll say here error and the way we check that one out is by providing wrong path so in my case i'm just going to add two dots and then once i save check it out in a console i'll have the error where it tells me that no such file or directory all right and now let's take a look at the practical example when streams come in handy now again this is going to be one of those videos where you don't have to code along you can just sit back and relax and see how i struggle and first what i want is to make it even a bigger file so remember d15 create big file i believe i had 10 iterations right so i'm gonna add one more meaning i'll add one more zero i'll stop my server right now again this is optional you don't have to do that and i'll remove the big file like so and then i'll run one more time the file with node and then of course this file is going to be way bigger so let me navigate to my folder just to showcase that and i'm looking for content and now the big file is 1.8 megs now once i have the big file i'll go with npm start at the moment i just have the stream example but if you want to see the whole code just take a look at the file number 17 and notice again we're creating a http server and i'm just using the read file stick method i'm looking for big txt the encoding is utf-8 and then i just place my variable my text one into res dot and method and effectively i'm just sending my big text file and let me restart the server here so let me go with npm start right now so let me select everything from this file and copy and paste and now if we navigate to localhost 5000 we should see a bunch of hello world now the problem with the setup is following where if i go to developer tools and if i take a look at the network and if i refresh yep this request was successful take a look at the size do you think it is the smartest thing to send these type of files over the wire and of course this is just going to make it very difficult to all your users because you're just sending large chunks of data effectively i'm sending the whole file and more specifically if i click check it out so i have the request url okay that is good the method is get now as you can see the content length is my 1.8 megs right and you'll see in a second that once we refactor this to read stream method that we're sending data in the chunks and again the best way to see that is by looking at the headers where at the moment i can see the content length and that one is at 1.8 megs but once we refactor that the setup is going to be different so at the moment i have this text i'm accessing that by read file sync so comment this out and let's set it up with our create read stream so i'll go with const and i'll call this file stream and this is going to be equal to fs and then create read stream now use the same address so use the same path and then i'll use the same encoding as well so let's go with utf-8 okay awesome and once we set up the stream remember we have access to to events file stream on and of course i'm going to be looking for the open and i'll have my callback function and we'll set that functionality up in a second and the second one of course is the error so go with file stream and then on and again we're looking for the event by the name of error and then in our callback function we can access the error and i'll simply pass it in in my response so if there is an error i'll just grab the error from my parameter and pass it in now as far as the open here instead of setting it equal to instead of going res dot end and then text file stream also have the pipe method so we can go to file stream and then pipe and what the pipe is doing it is pushing from the read stream into right stream so you can imagine that if we can read data in chunks we can also write data in chunks and what happens under the herd response object can be set up as a writable stream so we have our file stream so that's our read stream we have method of pipe so we're piping this into a writable stream and now of course i'll pass in my response object and if we go back to the browser and if we'll refresh now notice something interesting yeah still same request right to localhost 5000 still same size but if i take a look at the headers now i can see that my response headers are chunked so instead of sending our file back in one large instance we're sending it back in chunks awesome congrats on completing section number three node fundamentals and hopefully after watching the section you have a good general understanding of how node works and now that we're big shots let's apply that knowledge and build some servers shall we and we're going to start section 4 with the general info of how the web works more specifically how we exchange data on the web and we're going to do that with the help of few slides now if you're one of the people who's already reached a daily slide limit i hear you once we're done with these suckers i promise we'll mostly actually write code for the remainder of the course i do believe though that before we build an actual web server it's crucial for us to understand how it works under the hood and that way we'll have clear understanding of what tasks need to be done if something is iffy you can always go back to the slides you already know where they're located and also as we're going to be progressing with the course from time to time i will swing back to them when i'll need to emphasize a specific point with that said let's talk about how we exchange data on the web um it's safe to say that if you're watching this video you know how to use a web browser but under the hood the way it works every time we open up a browser and we type the url so the web address we're actually performing a request and we are performing a request to the server that is responsible serving those resources so for example when you look for cnn.com you're looking for a server that has those resources and then that server sends you back the response and the same works with youtube the same works with johnsmeld.com or whatever so you just pick a resource you say hey can i get this data and then server who is responsible for those resources just sends you back the response now that is done using http protocol and that's why these ones are called http messages so the user sends the http request message and then the server sends the http response message and that's how we exchange data on web and for the remainder of the course we'll be responsible for building such web server using node and more specifically express now i'll talk about it while we use express as well show you a few examples later on in a course but for now just remember that yes we'll use node but in order to make our lives easier we'll use the framework by the name of express js and lastly i would just want to mention that even though name server definitely sounds way cooler than the computer at the end of the day they're just computers whose job is to always make that resource available so yes those are computers and yes there are some differences for example they most likely don't have the graphical interface or the gui and also they're probably much bigger than your laptop but at the end of the day they are computers whose job is to always make sure that that resource is available because imagine if you would have a server that only works from eight to five so if you go to your website at i don't know six o'clock at night you cannot access the resource probably that's not the service that you would pick so next time when someone asks you if it rains does the cloud still work you know what to answer because at the end of the day when we talk about cloud cloud is just a bunch of these servers bunch of these computers connected together beautiful and once we have a general understanding how data is exchanged on a web let's also cover how http messages are structured please keep in mind that since it's going to be a big part of our job we'll come back to this particular slide more than once so if you're if you're about something just please be patient and i'll answer all of your questions as we move along with the course with that said the general structure for both messages is similar they both have a start line they both have optional headers a blank line that indicates that all the meta info has been sent and effectively headers are that meta info as well as optional body and before we continue again let me stress something so request messages are what the user is sending so for example if you open up the browser to search the web or that could be your web application because remember with web applications we also can make http requests correct and then response is going to be our responsibility so we'll have to set up a proper server that sends a correct response and in general when we talk about the request message in start line there's going to be a method then the url as well as the http version now we are mostly going to be interested in these two things in the method as well as the url now there's going to be a separate slide about the methods as well and don't worry we'll cover that in a greater detail once we cover them with actual code examples so i'll come back to that slide just understand the general idea that when we talk about methods effectively we're communicating what we would want to do so for example if i want to get the resource i'm going to set it up as a get request now if i want to add the resource then of course this is going to be a post request and then of course you can read the rest now why i'm displaying here this get because that is the default request that the browser performs since when we open up the browser we want to get some kind of resource correct that's why we're performing a get request and the url is just the address and that could be for example johnsmilk.com or that could be i don't know espn forward slash basketball both of them are just a web addresses now headers is essentially optional where this is a meta information about our request and just to give you a general idea how the headers would look like they would look something like this so it is a key value pairs now don't freak out as you know when you search the web you don't need to add them manually and the same is going to be with our server a lot of it is going to be taken care of but yes some things we'll have to add on our own basically this is going to be information about our message and then we also have optional body so when the user is requesting something if you just want the resource there is nobody there's nothing basically what to send however if we would want to add a resource onto the server yes then you are expected to provide that data and it's also called payload so again i might use them interchangeably so that's the general structure of the request message we have the start line we have the headers that is the information about our message as well as the black line which just indicates that we're done with the meta information and optional body which we'll use from time to time and now of course we need to talk about the response message so response message is what we're going to be creating again most of it will be done for us but some parts yes we'll have to do it manually and it's going to be our responsibility so the start line has the http version which most likely is going to be 1.1 then we have a status code and status text now when it comes to status code it just signals what is the result of the request so for example notice here this 200 that means that request was successful so that's what we're sending back and yes there's quite a few of those codes and as we move along with the course of course we will cover them but please please please don't rush over to the search engine and start memorizing the status codes pretty much as we're going to be building the application i'll tell you which code means what and for example 400 means that there was some kind of request error so the user was trying to request some kind of research and with 400 there was a request error now for example the code 404 means that the resource is not found so when i'm sending back the message i'm like hey listen here's the status code for the message if you are successful here's 200 if there was an error for example you get a 400 if the request is unauthorized then you can get 401 and hopefully you get the gist and yes of course as we're progressing we will cover more status code then again we have the headers where basically we provide info about our message our response message and again like i said you won't have to type everything line by line but effectively it is a setup of key value pairs and the ones that i would like to mention are these ones notice this content type we have text html that is when we're sending back the html but also our second option is going to be sending back the data so hopefully you are aware that when you're building a web application when we communicate with api most of the time we're getting back the json data because over the web effectively we just send over the string so if for example i have some kind of array we transfer this into application json and i clearly indicate that in my headers where i say that no i'm not sending text and html i'm actually sending a application json and then that application who is requesting the web application knows that hey from the server i'm getting a content type which is application json so for example in that case i could send back here this array with bunch of these objects and just to give you a real-world taste why don't we do this open up a new browser tab and i'm simply going to course api because i think there's going to be less data so there's going to be less clutter so go to course api here and then you can either pick the slides or you can just look at the home page and if you inspect and if you look in the browser tab you'll find a network and very useful one is this one where we can just look for all the requests we refresh and then check it out so these are the requests that browser performed and i'll talk about it a bit later why there's also this style css in fact that's going to be one of our first examples but take a look at this one so i have this course api and then forward slash and if you remember when we were building our original server what i said that if we have this forward slash that just means home page so if we're just navigating to courseapi.com and that is our homepage we simply add this forward slash now of course in the browser that's automatically added but that's why when we're setting up the server one of the cases is going to be if the user navigates to the homepage then we simply look for forward slash so if for example you go to the slides you'll notice that uh in this case i would have to refresh notice here i have the course api forward slash slides so that is already a page in my website correct so i have the home page course api and then i have the slides page where i have the slides and if you take a look if you click on it notice all the useful data that we get over here so for example this is going to be our request url which is going to be again course api.com so that tells me well what the browser is trying to get then check it out the method why it's get because that is default in the browsers every time you open up the browser and search something then of course you'll be performing a get request now check out this one the status code it is 200 why because everything is successful because servers send back the data then we have this remote address and basically that is the ip address for my server as well as notice this colon 443 and we'll come back to this one when we set up our own server because if you remember we were always setting up the 5000 so you're probably wondering well what is this 443 and don't worry again we'll cover that one once we set up our first server and then again we have response headers for example and we also have the request adders so as you can see using this network tab we can actually find a bunch of useful information now notice here in the second set of tabs i can see this response and preview so if you take a look at the preview this is going to be basically my site and also i can see the response so as you can see pretty much sending back the html so i'm sending back the website so you go into the browser you request a resource by default it is a get request and then in that body when the server sends it back this is what we get back so we get back the site so hopefully this gives you a clear understanding of how the http messages are structured and now let's dive into creating our own server awesome once we're done with the slides now let's start setting up our server and in order to follow along with the course you'll need to have a starter project and you can get it if you navigate to my site again the url is johnsmilk.com so navigate there in the project or in home page look for node express tutorial project in a home page is going to be at the bottom in latest project if you cannot find it there then look for all projects page or simply projects page then filter for node in order to save some time and then like i already previously mentioned any of these links will get you to the repo and then bravely get the repo in my case i'm going to clone it so i'll copy the url i'll bump up the sound size in my terminal navigate to the desktop get clone here and then i'm gonna get the repo and then once the project is on my machine i'm just gonna drag and drop and then the first thing that i would suggest doing is removing the remote url and you can simply do that by just wiping out the git folder so that way if you ever do decide you push this up to the github you won't have some dumb permission errors so i'm just going to open up the integrated terminal now in my case i'm not going to run the command but if you're on mac i suggest running rm then hyphen rf and then get now if you are on windows some students have just these two commands now i haven't tested them yet but some people have replied to my tweet that yes they do work and if you want to see the whole tweet just navigate to my twitter the handle is john underscore smilga and then as you can see here is the mac command and for windows i have these two so run this command and then in next video i'll give you a brief overview of the repo all right and before we get busy why don't i give you a brief overview of the ripple and if you take a look at the first project this should look very very familiar because essentially this is all the code we have written so far everything starting with our most basic application and then of course we also have our last one our http streams example so hopefully that is clear and if you ever need to jog your memory essentially this is just here for your reference and then from now on we'll work in a folder number two by the name of express tutorial and the idea is gonna be exactly the same where basically we build a bunch of examples and in the process we learned what is express and why we would prefer using express instead of straight up http module but again let me stress something where express is built on top of node and more specifically on top of http module so it's not like you can use express without node and in folder two the setup is following where there are gonna be some assets that i provided just so we can make more real world examples so hopefully that gives you a better idea how the express works and i'm not going to cover them right now for example methods public or navbar app once we get there i'll explain everything that's happening i think that it's going to be waste of our time if i do that right now however if you take a look at the final folder you'll basically see all our examples so the same spiel if you ever need to reference the code just navigate to the final look for the file name and then of course you'll find the code just keep in mind that in order to run this code you'll have to copy and paste and run it in the app.js why because in some cases there's going to be paths and since these files are located already in the final the paths won't match okay hopefully that one is clear as well and then we also should be familiar with these files as you can see i have package.json i have package.json lock and then app.js now of course app.js could be renamed server or whatever you would want but i already have in a package.json a script that spins up the nodemon and effectively we have successfully set up a node application so package.json is of course needed because we'll have some dependencies more specifically two one is going to be nodemod and the second one is going to be express and in order to of course keep track of those dependencies we have package.json and then if you notice i don't have the node modules here and of course the reason for that is because i don't want this repo to be massive and you can clearly see that in a git ignore where i have node modules included so when i was pushing this up to the github and of course i omitted the node modules since i added them in the git ignore and then in the package json like i said you'll find some dependencies and i'll talk about express once we get there the moment let's not worry about it the one that we should be familiar with is node one which is going to be watching our application and i have a script that sets up nodemon and passes in the amp.js so any changes in our project nodemon will be watching and restarting our application however we cannot do anything before we install all dependencies otherwise you'll just get an error so that's why the first thing that i would want you to do is navigate to the folder number two and the fastest way probably is just going to be cd and then take the project number two and drag and drop like so and then once you can see that you are in this folder so not in a root not in node express course but once you are actually in the folder number two before you do anything just run npm install first and then it's really up to you you can either wait for all the dependencies to be installed and then run npm start or you can simply chain it and say npm and once you run this one then of course you'll install dependencies and if you see in a terminal express tutorial that means that everything is correct and you can continue with the videos if you don't see that then please troubleshoot because none of the things that we're about to do next are going to make sense if you're not running the project number two with all the dependencies more specifically nodemon and express and lastly i just want to mention yes there's also this data.js and again this is one of the assets that i added that we're going to use a little bit later so if you see express tutorial in a console and the reason why it's there because that's the only line of code i have in my app.js that means that everything is correct and we can move on to our next topic and why don't we start the express tutorial part by setting up the server one more time with straight up http module and in a process let's struggle a little bit let's see why we would want to use express e in the first place so yes we'll build one more time server with http module however now of course we'll dive deep into the topics that we kind of skipped over before and in order to set up the server we know that we would need to require the module right so i'm going to come up with some kind of variable and in my case that is going to be http and of course the name is not required you can call this whatever you'd want but it is somewhat off a convention to call this hdp as far as the variable name then we go with require and we just go with http again keep in mind this comes built in node so you don't have to install it we didn't install when we ran npm installed in last video we installed two other dependencies but this one is built in so we don't have to do anything we just say require and it's always going to be available to us then we need to set up the server and again convention is calling the server but you can call this box bunny and in order to do that we go with http and then on this object we have a method by the name of create server now this method takes a callback which is going to be invoked every time the user hits our server and in this callback we have two parameters and again we can call them whatever we would want so again common convention is just shorten this up a little bit and call it request and res so rec and res and the first parameter references the request object and second one is the response object and at this point it should be clear why we have access to those two parameters because in the http cycle we have request message that is coming in every time user requests the resource and also we have the response message right so that's what we need to send out so that's why in this function that runs every time user hits the server we have access to rec and res so that way we can find info about the incoming request because it makes a total sense if we have access to that info i do want to know what is the method so what the user is trying to do i do want to know what resource the user is trying to get whether that is the contact page or about page and also i would want to

Original Description

Learn how to use Node and Express in this comprehensive course. First, you will learn the fundamentals of Node and Express. Then, you will learn to build a complex Rest API. Finally, you will build a MERN app and other Node projects. ✏️ Course developed by John Smilga. Check out his channel: https://www.youtube.com/channel/UCMZFwxv5l-XtKi693qMJptA 💻 Code: https://github.com/john-smilga/node-express-course ❤️ Try interactive JavaScript courses we love, right in your browser: https://scrimba.com/freeCodeCamp-JavaScript (Made possible by a grant from our friends at Scrimba) ⭐️ Course Contents ⭐️ ⌨️ (00:00​) Introduction ⌨️ (01:41​) What Is Node ⌨️ (02:56​) Course Requirements ⌨️ (04:16​) Course Structure ⌨️ (04:59​) Browser Vs Server ⌨️ (07:50​) Install Node ⌨️ (11:08​) Repl ⌨️ (13:27​) Cli ⌨️ (19:07​) Source Code ⌨️ (20:27​) Globals ⌨️ (29:34​) Modules Setup ⌨️ (32:46​) First Module ⌨️ (45:32​) Alternative Syntax ⌨️ (49:50​) Mind Grenade ⌨️ (53:47​) Built-In Module Intro ⌨️ (56:31​) Os Module ⌨️ (1:04:13​) Path Module ⌨️ (1:10:06​) Fs Module (Sync) ⌨️ (1:18:28​) Fs Module (Async) ⌨️ (1:27:32​) Sync Vs Async ⌨️ (1:34:29​) Http Intro ⌨️ (1:35:58​) Http Module (Setup) ⌨️ (1:40:53​) Http Module (More Features) ⌨️ (1:45:57​) NPM Info ⌨️ (1:50:19​) NPM Command ⌨️ (1:53:10​) First Package ⌨️ (2:02:52​) Share Code ⌨️ (2:09:04​) Nodemon ⌨️ (2:15:04​) Uninstall ⌨️ (2:17:53​) Global Install ⌨️ (2:23:22​) Package-Lock.Json ⌨️ (2:25:56​) Important Topics Intro ⌨️ (2:27:38​) Event Loop ⌨️ (2:30:47​) Event Loop Slides ⌨️ (2:37:46​) Event Loop Code Examples ⌨️ (2:47:07​) Async Patterns - Blocking Code ⌨️ (2:54:49​) Async Patterns - Setup Promises ⌨️ (3:00:35​) Async Patterns - Refactor To Async ⌨️ (3:06:05​) Async Patterns - Node's Native Option ⌨️ (3:12:41​) Events Info ⌨️ (3:14:44​) Events Emitter - Code Example ⌨️ (3:18:37​) Events Emitter - Additional Info ⌨️ (3:21:44​) Events Emitter - Http Module Example ⌨️ (3:25:10​) Streams Intro ⌨️ (3:26:18​) Streams - R
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from freeCodeCamp.org · freeCodeCamp.org · 0 of 60

← Previous Next →
1 React: Production Server Setup Part 2 - Live Coding with Jesse
React: Production Server Setup Part 2 - Live Coding with Jesse
freeCodeCamp.org
2 cookies vs localStorage vs sessionStorage - Beau teaches JavaScript
cookies vs localStorage vs sessionStorage - Beau teaches JavaScript
freeCodeCamp.org
3 Browser history tutorial - Beau teaches JavaScript
Browser history tutorial - Beau teaches JavaScript
freeCodeCamp.org
4 Graph Data Structure Intro (inc. adjacency list, adjacency matrix, incidence matrix)
Graph Data Structure Intro (inc. adjacency list, adjacency matrix, incidence matrix)
freeCodeCamp.org
5 React: Parameterized Routing with Next.js - Live Coding with Jesse
React: Parameterized Routing with Next.js - Live Coding with Jesse
freeCodeCamp.org
6 React: Dealing with jQuery Issues - Live Coding with Jesse
React: Dealing with jQuery Issues - Live Coding with Jesse
freeCodeCamp.org
7 setInterval and setTimeout: timing events - Beau teaches JavaScript
setInterval and setTimeout: timing events - Beau teaches JavaScript
freeCodeCamp.org
8 Browser and Device Testing - Live Coding with Jesse
Browser and Device Testing - Live Coding with Jesse
freeCodeCamp.org
9 Last Minute Updates - Live Coding with Jesse
Last Minute Updates - Live Coding with Jesse
freeCodeCamp.org
10 Post Launch Updates - Live Coding with Jesse
Post Launch Updates - Live Coding with Jesse
freeCodeCamp.org
11 React: Setting Up Google Analytics - Live Coding with Jesse
React: Setting Up Google Analytics - Live Coding with Jesse
freeCodeCamp.org
12 React: Masonry Layout - Live Coding with Jesse
React: Masonry Layout - Live Coding with Jesse
freeCodeCamp.org
13 Load Balancing Digital Ocean Droplets - Live Coding with Jesse
Load Balancing Digital Ocean Droplets - Live Coding with Jesse
freeCodeCamp.org
14 try, catch, finally, throw - error handling in JavaScript
try, catch, finally, throw - error handling in JavaScript
freeCodeCamp.org
15 Load Balancing: SSL Passthrough Setup - Live Coding with Jesse
Load Balancing: SSL Passthrough Setup - Live Coding with Jesse
freeCodeCamp.org
16 Graphs: breadth-first search - Beau teaches JavaScript
Graphs: breadth-first search - Beau teaches JavaScript
freeCodeCamp.org
17 React: Masonry Layout Part 2 - Live Coding with Jesse
React: Masonry Layout Part 2 - Live Coding with Jesse
freeCodeCamp.org
18 React: WordPress API Live Search - Live Coding with Jesse
React: WordPress API Live Search - Live Coding with Jesse
freeCodeCamp.org
19 Creating WordPress Custom Post Types - Live Coding With Jesse
Creating WordPress Custom Post Types - Live Coding With Jesse
freeCodeCamp.org
20 Dates - Beau teaches JavaScript
Dates - Beau teaches JavaScript
freeCodeCamp.org
21 Miscellaneous Front End Updates - Live Coding with Jesse
Miscellaneous Front End Updates - Live Coding with Jesse
freeCodeCamp.org
22 Merging a Pull Request from GitHub - Live Coding with Jesse
Merging a Pull Request from GitHub - Live Coding with Jesse
freeCodeCamp.org
23 React + Prettier + Standard JS - Live Coding with Jesse
React + Prettier + Standard JS - Live Coding with Jesse
freeCodeCamp.org
24 React: Sortable Responsive Table - Live Coding with Jesse
React: Sortable Responsive Table - Live Coding with Jesse
freeCodeCamp.org
25 Geolocation Sorting by Distance - Live Coding with Jesse
Geolocation Sorting by Distance - Live Coding with Jesse
freeCodeCamp.org
26 Tradeoff Matrix - Agile Software Development
Tradeoff Matrix - Agile Software Development
freeCodeCamp.org
27 The Definition of Ready - Agile Software Development
The Definition of Ready - Agile Software Development
freeCodeCamp.org
28 Getting first React job without experience - Ask Preethi
Getting first React job without experience - Ask Preethi
freeCodeCamp.org
29 React: Google Analytics Click Tracking - Live Coding with Jesse
React: Google Analytics Click Tracking - Live Coding with Jesse
freeCodeCamp.org
30 Submitting a PR to an Open Source Project - Live Coding with Jesse
Submitting a PR to an Open Source Project - Live Coding with Jesse
freeCodeCamp.org
31 Should I go back to school to get CS degree? - Ask Preethi
Should I go back to school to get CS degree? - Ask Preethi
freeCodeCamp.org
32 Hero Section CSS Changes - Live Coding with Jesse
Hero Section CSS Changes - Live Coding with Jesse
freeCodeCamp.org
33 Working Agreement - Agile Software Development
Working Agreement - Agile Software Development
freeCodeCamp.org
34 A day at Pennybox with Co-Founder Reji Eapen
A day at Pennybox with Co-Founder Reji Eapen
freeCodeCamp.org
35 React: Sorting and Filtering Data - Live Coding with Jesse
React: Sorting and Filtering Data - Live Coding with Jesse
freeCodeCamp.org
36 React: Sorting and Filtering Data Part 2 - Live Coding with Jesse
React: Sorting and Filtering Data Part 2 - Live Coding with Jesse
freeCodeCamp.org
37 React: Building a New UI - Live Coding with Jesse
React: Building a New UI - Live Coding with Jesse
freeCodeCamp.org
38 Definition of Done - Agile Software Development
Definition of Done - Agile Software Development
freeCodeCamp.org
39 Getting started with jQuery (tutorial) - Beau teaches JavaScript
Getting started with jQuery (tutorial) - Beau teaches JavaScript
freeCodeCamp.org
40 Making a React Blog with WordPress Content - Live Coding with Jesse
Making a React Blog with WordPress Content - Live Coding with Jesse
freeCodeCamp.org
41 React, NextJS, CSS - Live Coding with Jesse
React, NextJS, CSS - Live Coding with Jesse
freeCodeCamp.org
42 jQuery events - Beau teaches JavaScript
jQuery events - Beau teaches JavaScript
freeCodeCamp.org
43 React/NextJS Routing and WordPress API Custom Types - Live Coding with Jesse
React/NextJS Routing and WordPress API Custom Types - Live Coding with Jesse
freeCodeCamp.org
44 React: Working with API Data - Live Coding with Jesse
React: Working with API Data - Live Coding with Jesse
freeCodeCamp.org
45 React: Refactoring Components - Live Streaming with Jesse
React: Refactoring Components - Live Streaming with Jesse
freeCodeCamp.org
46 jQuery effects - Beau teaches JavaScript
jQuery effects - Beau teaches JavaScript
freeCodeCamp.org
47 More React Refactoring - Live Coding with Jesse
More React Refactoring - Live Coding with Jesse
freeCodeCamp.org
48 animate in jQuery - Beau teaches JavaScript
animate in jQuery - Beau teaches JavaScript
freeCodeCamp.org
49 "Finishing" My React Site - Live Coding with Jesse
"Finishing" My React Site - Live Coding with Jesse
freeCodeCamp.org
50 Starting a New React Project (P2D1) - Live Coding with Jesse
Starting a New React Project (P2D1) - Live Coding with Jesse
freeCodeCamp.org
51 React Project 2 Day 2: Learning Material UI - Live Coding with Jesse
React Project 2 Day 2: Learning Material UI - Live Coding with Jesse
freeCodeCamp.org
52 The Agile Manifesto - Agile Software Development
The Agile Manifesto - Agile Software Development
freeCodeCamp.org
53 jQuery: get and set with http, text, val, and attr - Beau teaches JavaScript
jQuery: get and set with http, text, val, and attr - Beau teaches JavaScript
freeCodeCamp.org
54 React Project 2 Day 3 - Live Coding with Jesse
React Project 2 Day 3 - Live Coding with Jesse
freeCodeCamp.org
55 The INVEST approach to product backlog items
The INVEST approach to product backlog items
freeCodeCamp.org
56 React Project 2 Day 4 - Live Coding with Jesse
React Project 2 Day 4 - Live Coding with Jesse
freeCodeCamp.org
57 Chickens and Pigs - Agile Software Development
Chickens and Pigs - Agile Software Development
freeCodeCamp.org
58 React Project 2 Day 5 - Live Coding with Jesse
React Project 2 Day 5 - Live Coding with Jesse
freeCodeCamp.org
59 jQuery: add and remove DOM elements - Beau teaches JavaScript
jQuery: add and remove DOM elements - Beau teaches JavaScript
freeCodeCamp.org
60 React Project 2 Day 6 - Live Coding with Jesse
React Project 2 Day 6 - Live Coding with Jesse
freeCodeCamp.org

Related Reads

📰
Beyond console.log: Advanced Debugging Workflows That Will Save You Hours
Improve your debugging workflow with advanced techniques beyond console.log to save time and increase productivity
Medium · JavaScript
📰
cgo Overhead Dropped 30%. When Should You Actually Care?
Learn when to care about the 30% drop in cgo overhead in Go programming and how it affects performance
Medium · Programming
📰
Why Everyone is Wrong About Website Development?
Web development requires a wide range of skills beyond just generating code with tools like ChatGPT
Medium · Programming
📰
The Silent Killer in Your Node.js APIs: Mass Assignment & How to Catch It Before Production
Learn to identify and prevent mass assignment vulnerabilities in Node.js APIs, which can bypass ESLint and SonarQube checks
Medium · Programming
Up next
Indian Express Editorial Analysis by Chandan Sharma - 1 JULY 2026 | UPSC Current Affairs 2026
StudyIQ IAS
Watch →