Node.js Crash Course for Beginners Tutorial - Learn Node Basics in 30 Minutes!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] in this crash course we're going to cover all the basics that you need to get started using node.js what is node.js well it's not a language it's a javascript runtime built on chrome's v8 javascript engine this means that you can run standard javascript outside of the browser so if you already know javascript there's no need to learn a new language for backend operations you can easily use node.js to create a web server an api and many other use cases node.js is really fast because it's non-blocking and runs asynchronous operations now there are some prerequisites before learning node.js you should have a good understanding of javascript including es6 plus features like arrow functions array methods like map filter and reduce async await promises modules etc you should also understand basic fetching from the client side and how to use json data if you're not up to speed on all of those i do have videos that can get you started the links will be in the description below now the first thing that we need to do is install node.js so go to nodejs.org and download the appropriate file for your operating system i'm running the most current version which is at the time of this recording 15.8.0 and you can check what version you're running by typing node dash dash version there are several differences in the way that javascript works in node.js versus in the browser in the browser we have the dom or document object model but in node.js there's no document and no elements so we can't call document.queryselector or anything like that in node.js and node there also isn't a window object instead we have the global object also the way that node handles importing modules is slightly different let's take a look at a very basic hello world example in node.js to demonstrate a link to the source code for this video will be in the description below all right so we have a server.js file here and the first thing we're going to do is create a const and we'll name that http and that's going to equal require and then http so node.js comes with a bunch of built-in modules and we need to import them as needed and notice the way here that we're importing the module by default node.js uses commonjs which has this require syntax you might be used to es6 modules where you use import and we'll get to that a little bit later so next we're going to define our hostname so we'll create a const hostname we'll make that equal to process.emv.hostname or localhost if that's not defined and then we'll create another const of port we'll make that equal to process.emv.port or port3000 if that's not defined so part of our global object is our process and then within the process we have our environmental variables so just like in the browser we might have window dot document but in node we don't have window so we have global dot process and many other methods but just like in the browser we don't have to type window.document we could just type document.queryselector right well here in node we don't have to type global either instead of typing global.process we can just type process so next we're going to create the http server so we'll create a const and then we'll name that server we'll make that equal to http.createserver now within that we'll have an arrow function and this is going to have a request and a response so we'll use the response and we're going to set a status code we'll make that equal to 200 and then we'll take our response and we're also going to set our headers we're going to set our content type and we'll make that equal to text plain and then we'll set our response dot end and we're going to send the text hello world lastly we need to start the server by having it listen on the port and host name provided so we'll say server.listen we'll give it the port the hostname then we'll have a callback arrow function in here we'll console log server is running at http slash and then we'll give it the hostname and colon the port so now to run this code we'll just open up our terminal we'll type node and then the name of the file which is server.js so server and we actually don't have to type js so it's just server node server and now we get server is running at http localhost 3000 so if we click on this we'll get localhost 3000 hello world and then if we open up the console and we go to network and we refresh this we'll see our localhost status 2000 and we can also see our content type is set to text plain so congratulations you just created your first web server so now to stop this process in the terminal we'll just press ctrl c and now it's no longer running so we've already seen the process method on the global object there are also a couple of other things that we have access to so if we type global and then underscore underscore we have dur name and file name so let's go ahead and console log these out all right then we'll save this open up our terminal and we can just run node server again you see that the file name is the full path including the file name and durname is just the full path so these can come in handy when we need to read and write to files on the server that brings us to the file system module in order to perform file system operations we need to import the fs module from node so let's start out by reading a file i have a high.text file here and it just says hello world in it so we're going to read it the first thing we'll do is we'll create a const we'll call it fs and that is going to equal require in fs and then we'll say fs.read file and we're going to pass in our high text and then that has a callback arrow function and that callback gives us an error and data so within that we'll say if there's an error then console.error the error and then return and if not console.log the data all right so let's save that we'll pull up our terminal let's clear that and then we'll say node server again and notice that we're getting a data buffer not the actual text from the document so to get the text we need to either add data dot to string so let's save that and give that a try so now we get the text hello world or instead of data.2string we can specify the encoding type so right here we can say this is utf-8 and now if we save this and we run it again we'll get the same thing with our text so now let's add a console log outside of our function so we'll say console log log from outside so i'll save this and then run it notice here that we get log from outside first and then our hello world text so this demonstrates the asynchronous nature of node so even though this code is first it takes it a split second to read that file while it's reading the file it's going to move on and run console log and then it's going to console log the data after it's been returned each node module also has a synchronous version the standard method is asynchronous which means that it will continue running the code in the background and then run the callback function when it has finished the synchronous version is blocking and it will stop the code execution until the process is complete so we can change this read file to read file sync so this is the synchronous version we're still going to pass all of this but there is no callback so we'll take that out and now because there's no error handling here we're going to wrap this in a try catch so we'll say try and then catch we might have an error here so we'll console error the error so let's turn this into a const we'll call this data and then after that we'll console log the data so now let's run this one and this time we get hello world first and then log from outside so it waits for this to finish before it continues and then it runs the console log from outside second now instead of importing the entire fs module we can also do destructuring so for these instances we could have destructured and said we only wanted read file and read file sync and then instead of fs.read file we would just call read file sync so next let's look at writing files so let's change these to write file and write file sync and write and we'll get rid of all of this all right so we'll create a const we'll call it new content and that's going to equal this is some new text and then we'll call right file we'll pass it our high text file and then we'll insert our new content here and this is going to have a callback and we might get an error in this callback so we'll grab that and then we'll say if there's an error then we'll console.log the error and return and if not we'll console log content written all right let's save that and then let's run this so open up the terminal and let's run node server again and we have content written so let's go over to our high text and we see this is some new text notice here that the content has been replaced it no longer says hello world so that's the default behavior of write file and we can change this behavior by adding a flag so if we go back in here and then after the content we'll add an object and this is going to be flag and we're going to give it the flag of a for append so now we save that and then let's run it again content written go back over here and so now we have this is some new text and right after that this is some new text so it's appending it right after so again we can use the synchronous version which is write file sync so again we'll need a try catch we'll say write file sync we'll pass it our text file and we'll pass it the new content and then we're going to console.log content written and then if we have an error we'll console error the error all right so let's save that and again open up our terminal content written we go to our terminal here and again it overwrote the file because we didn't pass it any flags so instead of messing with the flags we could just use the append file method so here we could just change this to append file and we don't need the sync and then let's change this new content we're going to add a new line by adding a backslash n that's a newline character and this is some more new content all right and then we're not going to use the synchronous version so let's get rid of the try catch so this time we'll use append file we'll give it the text file the content and then we have our callback with a possible error where if we have an error we'll console error the error and then return and then if not we'll console log content written all right so let's save that and we'll run that again node server and we have content written and we go over here and we have our new line this is some more new text that's much easier all right we can also rename files so that's pretty easy let's go up here and let's bring in rename from the fs module and we won't need this and then everything is almost the same so we're going to rename we're going to give it our original file name and then the new file name so let's say hello dot text and then again we might have an error so we'll console error that return otherwise we'll say file renamed all right so we'll save that go back to our console run it again and now we can see this high text has been deleted so let's open up our files and we can see now we have a hello text instead of a high text and there it is it's just been renamed alright and then we can also delete files and you might think that the module is delete but it's actually unlink all right so we'll import the unlink and we'll change this to unlink and then we just need to reference the file which now is hello text and then we possibly might get an error so we'll do all the same stuff again and then we'll just say file deleted all right we'll save that and run it and now we can see hello text has been deleted open up the files and we can see that it is gone all right next let's create a simple module so in my main file i want to add some numbers so i'm going to say const add nums is going to equal require and then we're going to pull in a file that we're going to create called add nums and then after that i want to create a const called sum and that's going to equal add nums and we're going to pass it 2 and 2. and then after that we'll just console log sum so we want to create this file now add nums let's go over here we'll create a file add nums.js and then within this we'll create our function so function add nums is going to take a and b all right so here we're just going to return a plus b and then we need to export this so we say module dot exports add nums all right so let's go back and so we have this we're importing it here using require so let's open up our terminal and let's say node server and we get the answer two plus two equals four and we can do this using es6 modules as well so if you're used to that export import we can go to add nums instead of module.exports we can say export with no s just export and then we wrap add nums in curly braces so export add nums just like that and now in our server.js instead of using the require syntax we can say import and then add nums and that is going to be from dot slash add nums now there's two different ways to go about this we can either change our file extension from js to dot mjs which is a module javascript or we can add an attribute to the package.json file so let's try the first way so if we go to our files we'll need to rename these to dot mjs and then on our server where we're importing it we do have to specify the extension dot mjs all right so we save that all right so now we can run the server again but this time we have to use nodeserver.mjs we have to specify the extension here and now we get 4. i don't really care for this method so let's change these back to js and then the other option is to alter our package json now we don't have a package json yet so this is part of keeping track of node modules and your project information so to get our package json we're going to say npm init dash y so we're going to get into npm in a little bit but for now we're just going to run this and it's going to create our package json so this has the name of our project a version optional description it thinks that this is the main file it's actually server and then we can run some scripts and we're going to go over this in more depth in just a little bit but in this we're just going to add type and then module so now it knows that we should use es6 modules so let's save that and now we still have to specify the dot js on here when we're importing so let's save that go to the terminal and let's run node server and we get our answer now this time we didn't have to specify server.js just node server but we do have to specify the dot js here also note that when using es modules in node we no longer have access to require exports module dot exports underscore file name or underscore dur name so because of all of these minor gotches you're most commonly going to see the common js syntax of module.exports and require so we're going to continue to use those but i just wanted to show you that you can use es modules all right so now let's go back to the http module and we're going to create an actual web server we'll start with that basic example again so we're going to create a cost of http will make it equal to require http so we'll bring that module in and then we're going to use that http dot create server and then that has an arrow function where we have a request and a response so we're going to take that response we're going to set the status code to 200. now is a pretty good time to look at all of the different status codes so the code ranges are 100 for informational 200 are success codes 300 are redirects 400 are user or client errors and 500 are server errors so common ones you'll get 200 is ok that means everything is good 301 is a resource moved 404 is not found and 500 internal server error so now back in the code we'll use the response to set our header we're going to make the content type text plain again and then we're going to response dot write hello world and then we have to response dot end after that we can listen we'll listen on port 3000 and then we are going to console.log server is running all right so pretty simple let's save that and run it open up our terminal node server and it says server is running so now if we go to local host port 3000 now we get hello world again all right so let's kill this control c that's always good practice to set our port so we'll say com support is equal to process.emv.port or 3000 and then we'll take port here and we'll just replace that 3000. we always want to set our port in our environmental variables once we deploy so this time i'm going to set our http to a constant so we'll say const server is going to equal http and then create server and then here we'll say server.listen now the last time we've specified our hostname and we can do that if we don't do it then it just defaults to localhost so we'll just change this console logout to server is listening on and then the port so now i also want to show you that we can write and then we can write some more so let's alt shift down and we'll say hello world again and then we can end it or within the end we can also pass data so we can say the end so let's save that and then run it again server's listening on port 3000 so let's open that up and now we have hello world hello world again and then the end all right so that doesn't look very good this is not great so let's look at sending some html so that is pretty simple so here we just need to change our content type to text html instead of plain and then instead of writing all of these we're going to get rid of the writes we actually don't need any writes if we just have one thing that we want to write so on the end we're going to change this to some html so we'll just say h1 and then we'll type hello world we'll save that and then now our server is still listening so we saved it but we have to restart our server so if we go back here and we refresh it still has the same thing so we have to restart our server so let's kill the server control c run it again and then let's go back to our browser and now if we refresh we get an h1 with hello world all right so now we're going to put everything that we've learned all together we're going to send an html file so we need to access that file in order to do that we need to import the file system module all right so we'll create a const of fs and that's going to equal require fs and then everything else is going to be very similar so we're going to create our server we're going to set our status code set our header and then instead of res.end we'll use fs.read file and we'll pass in the file that we want to read it's an index.html and then we have our callback which has the error and data so then we'll check to see if we have an error we'll console error the error and then res.end else will res.right the data and then res.end now to shorten this since we're just sending one thing we could just res.end on the data and remove the right let's save that and i'm going to show you here we just have an index.html file it's just a very simple file that has hello world and a little bit of styling this is not an html or css course so we're not going to look at that too much so let's go ahead and run this so now again our server is already running so we need to kill it and then run it again now let's check it out in the browser and there we go hello world all right next let's look at some basic routing right now we're sending this file no matter what url or method that we're using so if we go up here localhost.3000 slash about we're still getting the same file we want to be able to route certain files to certain urls so the first thing let's do is in here let's go ahead and console.log our request.url and our request.method so you can see these all right so let's save that now again we need to restart the server so control c and then run node server now it's listening and as we refresh the browser watch our console now we can see we went to slash about using the method of get and looks like we're also looking for a favicon if we go back to just slash just localhost 3000 and we'll get slash which is just the root and then git and again we're looking for the favicon just ignore that one so that's how we can tell which url we're going to and what method okay so let's go ahead and kill that server and then we'll make some alterations here so let's get rid of the console log so now instead of hard coding this index.html we need to do some checks first and then pass that in as a variable so let's create a variable of path so we'll say let path equal and let's just say dot slash that's the current directory now if you have many different pages you're probably going to want to create a view folder and put everything in there for now we're just demonstrating so we're just going to keep the root directory here so now let's use a switch so we'll say switch and we're going to pass in our request url and then we'll say case slash so if it's the root directory then we're going to add to path index.html and then break and then we'll say case slash about so if we go to slash about we'll add to the path about.html and then break and then we'll have a default so anything else is going to go to 404.html and then break all right and so then we have this path here that we can now pass right here and then everything else will be the same we just need to create this about and this 404 so let's go over to our files here so in our index i'm just going to change hello world to home and then let's just copy everything we'll save that we'll create a new file we'll say about.html we'll paste in the same html we'll just change this to about and then we'll create a 404.html paste that in and change this to 404. all right so let's close those out and we can save this and then let's run it node server listening on port 3000 let's bring the browser over now if we refresh this should change to home there we go and then if we go to slash about we get the about page and if we go to anything else i'll just type something in there and we get the 404 so again back to slash and we're back to home now back in here we should probably change the status code i have the status code to 200 every time so we should probably move the status code 200 here because it's not always a 200 if we have a 404 so let's go ahead and cut that and if we go to index.html that would be a 200 about would be a 200 but the 404 that is going to be a 404 we can also easily do redirects so maybe instead of showing a 404 we just want to redirect them back to the home page so instead of this default going to the 404 we'll take the path out and we're going to change the status code to 301 that's going to be a redirect then we're going to set res.set header and we're going to set our location to flash all right so let's save that and then run it again it's still running so we have to restart it we'll go back to our browser and now if we go to some random url it's always going to go home unless we go to slash about and then again if it's just something random it's going to go home so it's redirecting all right now let's talk about npm packages included with node is a package manager called npm node package manager node includes a lot of great modules already but there are even more remote packages available that you can download and include in your projects we do that by using npm in our terminal so let's pull up the terminal so like i showed you before we used npm and knit dash y to initialize our project and create a package.json file this time we'll do npm init without the dash y so the dash y accepts all of the default options this time we'll take a look at the options all right so it's going to ask us a package name it defaults to the folder name we'll just say node demo and then version we'll just stick with one a description is optional i'll just hit enter entry point server.js that's what we want a test command we'll just leave it blank for now git repository is optional keywords are optional author is optional we'll say code stacker and then the license the default is isc that's fine we'll just hit enter and then is all of this okay we'll say enter for yes and we're done so now we can open up our package json and we can see all of the stuff that we entered right in here now before every time we made changes to our server we would have to stop our server and restart it we're going to install a package that is going to make our lives so much easier it's called nodemon so we can do that a couple of ways we'll open up the terminal again and we can say npm i for install and then dash g for global nodemon and that will install nodemon globally on our computer but i prefer to set it as a dev dependency of the package so we're going to say npmi dash capital d or dev dependency and then nodemon all right so we'll hit enter there it's going to download and install it now if we look in our package json we can see dev dependencies nodemon i prefer to have it in our package just in case another developer doesn't have it installed globally so now notice after we installed these open up our files and now we have this node modules folder and this contains all of the modules and dependencies for nodemon and for any other modules that we might install you should never have to open or make any changes to anything within the node modules directory and when sharing your code with someone you'd never want to include that folder either because it contains a lot of files and can get very large so in a bit we're going to upload this to github and we don't want to include the node modules folder so we're going to create a file here and we're going to call it dot get ignore and then within this file we're just going to specify node modules we want it to ignore our node modules folder and not upload it in fact if we were to download this project from github it would come without a node modules folder so if i delete this node modules folder i can easily reinstall it by just typing npm i i for install now it's going to go ahead and download all of the dev dependencies and packages that we need for this project as defined in our package json file now let's edit our scripts to help us out here alright so we already have a node start which is going to start our node server.js i'm going to change build to dev and for this one it's going to be nodemon server all right so node mon is a node monitor anytime we make any changes to any files it will automatically reload the server for us so now to run these instead of typing node server to start the server we can just type npm run and then one of these scripts either dev or start so it will say dev now we can see nodemon is running and it has started the server and it's watching for any changes so if we go into our server and let's go back here and i want to change this back to the way we had it by showing that 404 instead of redirecting all right so we're going to say the default we're going to add this path here and that's going to be the 404 and then this is going to be a status code 404 so now let me open up the terminal and then watch whenever i save it it's automatically restarted so now if i bring the browser back in and i'm not going to refresh i'm just going to go to some random url and we get a 404 and then if i go to about i get about and then home so in development you'll want to run the dev script and then on the server we'll run start so let's find out how to do that next we're going to deploy this to heroku all right so the first thing that we're going to do is we need to upload this to github so we're going to go over to our source control and first we need to initialize a repository so let's do that and then we need to make a commit so again this course is not on git and github i do have git and github videos links will be in the description so we're going to make a commit here we'll just say initial commit all right and then we're going to upload this to github so we'll just click this little cloud icon here then i'll upload this we'll say node crash course and i will make this a private repository for now and that's going to upload it and we can open it in github if we want but what we're going to do next is go to heroku so on heroku let's zoom in a bit here so i've already logged in it's free to sign up and log in and then we're going to create a new app and you can name your app or you can just leave it blank and heroku will name it for you so we're just going to create the app and now we need to select our deploy method you could use the heroku cli or we could just connect directly to github that's the easiest way so we'll say github go down here and i'm already signed into github through heroku so i just need to find that repo that was node dash crash course and then we'll search and there it is so we're going to connect and then we'll deploy this branch and you can see here that it is running everything it's building it's deploying build successful and there we go it has been deployed and we can view it right here we'll click that and there it is we have this awesome url gentle beach 579 all right so now if we go to slash about that works and then anything else goes to 404 and we can go back to the home right there all right so we have built our first node web server and deployed it to heroku congratulations hope this crash course helps you out and get you started using node.js i'll have more in-depth videos on node.js coming up soon including how to use the express framework like this video to help me out and subscribe if you haven't already for more videos like this you
Info
Channel: codeSTACKr
Views: 17,359
Rating: undefined out of 5
Keywords: nodejs, node tutorial, node js tutorial, node.js tutorial, nodejs tutorial, learn node.js, learn nodejs, node js, node.js, nodejs beginners, node, what is node.js, what is nodejs, node js tutorial for beginners, server side, mean stack, js, server, web development, javascript, beginner, backend, node js crash course, webdev, app development, lesson, tutorial, deno, nodejs basics, php, fullstack web, http, heroku, heroku node.js, deploy nodejs app to heroku, web development 2021
Id: 2LUdnb-mls0
Channel Id: undefined
Length: 33min 48sec (2028 seconds)
Published: Thu Feb 18 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.