Node.js Crash Course Tutorial #2 - Node.js Basics

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
or rather than gang so for most of this course we're going to be using node to power the back end of a website by creating a node server and then using that to handle browser requests and responses well first of all in this video I just want to play around with node a little bit on our computer first without creating a server or a website just to get a feel of the basics so that you're more comfortable using node so we've already seen how it can create a JavaScript file on our computer and then run that through node and we do that by opening up a terminal in the project directory now that could be an integrated terminal like this in vs code or you could use command prompt or something else and then say node and then whatever the file is called in this case test so press ENTER and that runs the file and inside this file we can write any valid JavaScript so for example I could create a function called greet and that function takes in a name parameter and over there inside the function will just console that log and we'll do a template string which says hello and then output the name that we take in so this right here by the way a template string we can output variables inside them using this syntax okay so let me just comment this stuff out first of all and then down here we could say greet and our plus in Mario and then also we'll call it again greet and pass in a different name Jasha all right so if I were to run this I can do by saying node test and that's going to run this file and it's going to run this function twice and log this out twice with a different name each time so that's how easy it is right to run a JavaScript file through node on our computer so basically we can use the same JavaScript language here that we normally use on the front end of websites in a browser and if you like variables functions objects classes etc but there are some differences too the first being the global object so in node we get access to a global object with several different methods and properties attached to it that we can use out of the box now this is a bit like the window object when we work with JavaScript inside the browser so let me just bring a browser over here so we can look at this window object inside the console so if I just type out window like this we can see this object with a load of different properties and methods available to us inside the browser okay so this window object inside the browser is the browser's global object and it has methods like set timeout alert and all that kind of jazz so we can use all of those methods and properties out of the box inside the browser for example I could use a set timeout and an alert and these are available to us in JavaScript inside the browser so if I press enter then we should get an alert after three seconds okay like that now I don't have to explicitly say a window dot set timeout because it's attached to the window object after all this is the global object and so it's presence is implied so we don't have to do that we just use whatever the method name is or the property name is and we can do that directly inside the browser so inside the browser the window is the global object but in node our global object is not window but global and that represents the global context in a node environment so then I've gone ahead and created this global JS file so we can have a look at this global object right here and the first thing I'm gonna do is just say console dot log and we're going to log the global object to the terminal down here so now let me run this by sync node global like so and we can see this global object and attached to it are a few different things so we can see we have these methods right here we have clearance of all cleartimeout set interval etc and they are available to us inside nodejs so for example i could come down here and I could say global time outs like so and in here we can do the same thing we can pass a function and inside the function I'm just gonna say console dot log in the timeout like that and I'm going to run that after three seconds like so so again I'm going to open up the terminal and I'm going to run node global and then after a few seconds oops we get an error because I've spelt global incorrectly so let me do that again clear and then run the file so node global and this time we get the global object first but then after three seconds we get this message as well in the timeout okay let me just comment this thing out at the top so we're not logging that to the console every time we run this file but anyway this is us now using a method available to us on the global object in node now same as window we don't actually have to explicitly type global it's just available to us out of the box so let me save that and run this again just to make sure it still works we wait three seconds and then we should get this log to the console which we do awesome so that's one of the things available to us another one is set interval so let me scoot this down a little bit and I'm going to say Const and int for interval is equal to set interval and in here we're going to run a function and that function is going to run every three seconds or rather every second will do so 1000 milliseconds so the difference between set timeout was set interval as you probably already know is that this keeps on running the function every one second this is only going to run it once after three seconds okay so now if I go over here I'm gonna say console dot log in the interval like so now let me run this again node global and we're gonna see every second now I'm in the interval and we see this after three seconds as well in the timeouts now this is going to go on and on and on forever so we need to cancel out with the process by doing ctrl C and we cancel out with that node process it stops running the file so now what if we want to stop this well we can access the clare interval method as well so inside set timeout I might say Clare interval and we pass through what interval we want to clay oops spell this correctly and it's this one right here int so now what's going to happen is this is going to run every second until we reach three seconds at which point wearing this function and at that point we clear the interval and that stops this from carrying on so let me save this file and preview this again note global in the interval in the interval then in the timeout and at that point it stops okay cool okay so I want to show you just a couple more things that are available to us in nodejs without was having to do anything and that is two properties the Durr name or directory name and the file name so let me log both of these to the console and is underscore underscore dur name and then I'm going to duplicate that and change this to file name and what these two things do for us is first of all this won't do name gets as the absolute path of the current folder that this file is in and this one gets us the absolute path of the folder with the file name added on as well so if I save this and try to run node global again in fact let me comment these things out first save it and run it know to global and we see this is the first one a full absolute paths of the directories that we're currently in and then this is the second one which is the same but with the file name added on as well now this especially is useful when we're working with node to get the current directory of our file because we're sometimes interacting with different files and we need to formulate paths between them okay so these two are quite useful now like I said the global object in node is different from the global object in window so some of the things in the window object rather most of them we can't actually access things like Dom methods so for example I couldn't access the query selector so I couldn't say console dot log and then documents dot query selector that wouldn't work let me save it and try this node global and we get an eric documents is not defined because documents is in the window object and we don't have that in the global namespace of node j s but that's okay because we don't really need to do all of that stuff that we want to do in a window like interact with a webpage we're going to be using nodejs on the back end or on the server side so we don't need access to all of those things available on the window object alright then so sometimes we might want to split our code into multiple different files and then import and export things to and from those files and this way we're going to keep our code much more modular reusable and also much easier to maintain as well and we're not just dumping all of our code into one single file so what I've done to demonstrate this is create two new files modules and people and the first thing I'm going to do is just paste in a bit of data into this constant right here people into the people file so this is just an array of strings which are people's names and I'm also going to log those to the console down here so console dot log people and I'm gonna save it now what if I want to import this people file into this modules file well I can do that using a require statement now the way this looks is by saying Const and then giving this constant a name you can call it whatever you want I'm going to call it X Y Z and set it equal to require and this inside is going to be a relative path to whatever file we want to require our import now we're going to say dot forward slash and that means look in the same directory that this file is in since that's where the people file is and then we want to get the people file so now we're requiring or importing this file into modules so if I run this modules file what's going to happen well let's take a look node modules and now we see this array logged to the console and that's because we log it right here so when we require another file automatically node looks for that file it finds it and it runs that file which is why we see this log down here because it's running this now what if I try to log out this what is this value gonna be well let me say console dot log and we'll say X Y Zed and save it and run this again note modules and we see that this value is an empty object so this right here is actually returning an empty object to us and I'll explain that in a second I just wanted you to that it's an empty object now also what if we try to access the variable inside this file from over here can we do that well let's say console dot log people and save it and then let me run this again and know we can see that people is not defined so just because we import a file right here it doesn't automatically give us access to the things in that file we can't do that we can only access them from inside the file ok so what then if I wanted to access people inside this file well we have to manually export this thing right here and then whatever we manually export is going to be applied to this constant right here now we saw a minute ago that this is actually an empty object when we logged it to the console and that's because we're not manually telling this file to export any kind of data or properties so how do we do that well we do that by saying module dots exports and this is saying look I want to export something manually from this module this file and we set that equal to something and whatever we set this equal to is what is going to be returned to us right here and then this constant will be equal to that value so if I set this equal to hello then this X Y Zed right here is gonna be hello so let's try that let me delete the second console log and save it and come down here and say node modules and now we can see first we get this logged because we do over here and then we get hello because that is the value of module 2 exports and therefore that is the value of this thing right here so if I want to export this I just need to say module that exports is equal to people simple as that and now X Y Z is going to be equal to this thing right here people and it doesn't matter that this is called XYZ and this is called people they don't need to be called the same thing so if I save this and preview then we can see now when we log X Y Z we're logging this a sec time because that is what we exported all right so that's how we export a single thing what if we want to export multiple different things so let me just paste in another constant ages which is equal to an array of ages this time numbers and let's say I want to export this as well how do we do that down here because at the minute we're just exporting one thing well this right here can be any value so I could say that this is equal to an empty object and then I could export different properties on this object so I could say people is going to be people so adding a property to this object called people and we're setting the value of that property to be people now this and this doesn't have to be the same name but I like it to be that way because then we can use a shortcut which is just to say people and that is when this and this is the same name it can do that and it does this under the hood it adds a property of people and sets equal to the people constant okay so I'm exporting people and also ages and that's what we're going to do so now we're exporting an object with these two properties on it people and ages and they're equal to these values at the top so let me save this now and if we go over here and still log X Y Z to the console we should see an object with those two properties so we can see right here this object with these two properties people and ages and we can now access both of those by saying X Y Z dot people for example and X Y Zed dots ages so save that and I'll put those and we can see the output separately right here awesome now a nice way to import multiple different things from a different file is to use destructuring and that looks something like this we can say an object right here and then whatever properties we want to extract from this object that's being exported so if I want to just extract the people from this file I can do that inside this object right here this destructuring object by saying people and this now does have to be same name as the property I want access to all right so now all I'm doing is importing people and I don't have to say XYZ dot people I just have access to people but I don't have access to XYZ because that's not defined anywhere or ages and I can demo that let me save it and say node modules we can see ages is not defined but we get people right here which is defined we don't get an error father now if I just delete this we should see this works node modules and we can see this right here so if I want both of those things I can say okay well get me people and ages and now if I output those it should work so node modules and we can see both of those right here so you'll see me using this kind of pattern in the future when I'm importing several different things or just maybe one thing from a different file so now we've seen how to export and also import our own made files but no js' also comes with some core modules built into it and we can also require those as well for added functionality so let me down here say for example Const OS which stands for operating system equals to require and we're going to require the OS core module so this is built-in to node itself I don't need to create an OS file it's already built into node and I'm importing that into this file so now down here I could say console.log OS and this is an object with a lot of information about the current operating system that this is running on so I could save this and say node modules and we get that big object right here okay now a couple of the different properties we can use on this object or rather methods in our case are the platform which is a method and that finds us the platform that we're running on and also we'll say the home directory so home dir and there are other things as well I'm just showing you two examples right here so save that and really and this time we can see that the platform is Windows win32 and this is the home directory on my computer for slash users slash Shan okay so that could be useful if you need to find out information about the operating system and there's loads more things on that you can play around with it and see for yourself so there are several different core modules in node J s OS is one of them about the operating system and another one is the file system so one of the things that we can do with node is use its filesystem core module to do things like read files create files and delete files on our computer now this ability to interact with the filesystem on a computer with JavaScript is something that can't be done without node and it's a really important feature to have for any kind of computer program or server-side code that needs to be able to do that needs to be able to read files or create files so I'm going to show you how to read files write files create and delete directories and also delete files as well so first of all we need to import the core module that we need to do all of this interaction with the file system and that is the fs module built into node so I'm gonna say Const FS and you can call it what you want but the module itself is called FS as well and normally you will see people name and get this all right so FS stands for file system by the way the first thing I'd like to show you is how to read files and to do that we say FS dot read file now this takes in two arguments the first argument is a string and it's a relative path to the file that we want to read now I've already created a folder right here called Docs and I've created a file inside it called blog 1 txt and it says hello ninjas so I want to read this file so I need to pass a relative path to that file right here so I will say dot forward slash to say in the current directory then in to the docs folder then blog 1 dot txt so I want to go out and read that file the second argument is a function and this function will fire when this is complete so this method right here is asynchronous and that basically means that it takes some time to do now once it's done it will fire this callback function ok and inside this callback function we take two things an error if there was one and also the data the stuff that we read from the file so what I'd like to do first of all is check if there was an error first of all and if there was let's log that to the console so console dot log error ok down here I also want to log to the console the data so console dot log data like alright so now let me run this so if I say node fails to run this file which is called files it's gonna run this hopefully try and read the file and we get a buffer that is this thing right here being logged to the console okay so a buffer is basically just a package of data that's been sent to us when we read this file now we're going to talk a bit more about buffers and strings later on but for now if we want to see the actual string data this in text format we can just use the to string method on this data and it will turn the buffer into a string so we can read it down here so if I run this again node files we see hello ninjas all right then I said that this was asynchronous right and it takes some time to do and also it doesn't block our code now what do I mean by that well I mean it's not going to stop the code from carrying on down here and executing all the lines of code even though is taking some time to do it doesn't sit around and wait for this to happen before it moves on it carries on with the code and then when this is done you fires that callback function so let me demo this I'm gonna say console.log and I'm gonna say lust line since this is the last line of code and I'm gonna run this so node files and we see that last line is logged right here before hello ninjas which is up here and that's because like I say this fires it starts the process of reading this it takes some time to do in the meantime javascript carries on down the file it executed this first then once this is done we fire this callback function and then this is logged to the console okay now let me just show you this in action this error if I change this to like block 12 or something that doesn't exist and then try to run this again we get an error up here and an error object and it says no such file or directory okay all right then so that is how simple it is to read files now let me comment this out and go down to writing files down here which is equally as simple so again we say FS this time use a method called write file and this time we take in three arguments if first argument again is a relative path to the file we want to write to well I'm going to say I want to write to this blog 1 dot txt file so dot forward slash to say the current directory then we want to go into Docs then forward slash blog 1 dot txt ok so the second argument is the text that we actually want to write to this file so say for example I would write hello world instead of hello ninjas well I'm going to write that here hello world hello world not ll world and now when I run this in a second it's going to replace whatever is in this file with this content right here hello world okay so the third argument again is a callback function because this like before is asynchronous this is going to take some time to do it's going to start it carry on down the code when it's finished it's going to run at this callback function all right so in here let me just say console dot log and we'll say file was written ok so let me now save this and come down here and run the file note files and we see this log to the console and if we go to blog 1 we see hello world before it was hello ninja so it replaced that with the new content ok so what if we try to do this right here with a file that didn't actually exist so say for example blog - let me change this to hello again what would happen now because this doesn't exist would we get some kind of error well no what would happen is it just creates this file for us if it doesn't exist so if I run this again node files we see file was written twice and now we see blog to up here as well hello again alright so there we go that's writing files again really simple to do alright so down here let me talk about how we work with directories so say for example I want to create a new folder called assets or something like that well I can do that by using a method on the FS module called MK dir that stands for make directory and this is going to make a directory for us we just need to specify what directory to make him where so I'm going to say make in the current directory dot forward slash then create a directory called assets again this is an asynchronous task it takes some time to do we fire a callback function when this is done and inside this callback function we can take in an error object if there was an error so I'm gonna check if there's an error first of all if error then we'll log that to the console and then down here as well I'll also say console dot log folder created okay alright then so let's run this and see if it works node files and we see now this assets folder is created awesome now what happens if we try to run this again because now we already have the folder so if we run it again we're gonna see we get an error object right here file already exists so it's saying look there's an error because this folder already exists and I can't remake it it's already there so before we run a code like this it would be a good idea maybe to check if the folder exists first of all and then only run the code if it doesn't exist all right so let's do that I'm gonna say if and then inside parentheses I'm going to use a method on the FS module called exists sync and this is a synchronous method meaning it will block the code it's only gonna take a very short amount of time to do though and it's gonna check if something exists now I want to check if the assets folder exists so I want to say dot forward slash assets like so now inside curly braces I want to output this stuff right here but at the minute this doesn't make much sense because if it exists then this is going to return true and it's going to try to make it but we don't want that because we only want this to run if it doesn't exist okay so I want to reverse the result of this and I can do that by placing an exclamation mark in front of it so now if this does exist and it returns a truth value the right here will negate it and send it into a false value therefore this will only run if this doesn't exist okay all right so let's try this and if we come down here again and say node files now we get no error because it's not running this code so if I delete this though let me just delete it and run it again then it should run and create that folder foras again all right okay so let's also add an else clause to this so we can remove the directory so we're saying okay only run this code right here if this doesn't exist this assets folder if it does then we'll run this else clause and we'll remove the folder instead so to do that we'll say FS dot R M dir remove directory what do we want to remove well we want to remove dot forward slash assets again this is asynchronous we fire a callback function when this is done and inside the callback function we can take in the error object if there is one we're going to log that to the console if there's an error so if error console dot log error and something's going wrong here okay I need to just put parentheses right here and take them off here and then down here I want to say console dot log folder deleted okay so let's try all this out I'm gonna say note files and it deletes the folder because this run and if I run it again note files it creates the folder this time because this run and I can keep on doing this and it's going to delete and create the folder depending on whether it exists or not already pretty good right okay then so one more thing I want to show you how to delete files and this is pretty simple but again I want to make sure that a file actually exists before we're going to leet it so I'm gonna do a little check first of all to say if F s dot exists sync like with it before and I'm gonna look for a file which is in the docs folder and then delete me dot txt so I'm going to create a new file inside Doc's called delete me txt we don't need to put anything inside it but now this is going to look for this delete me file and if it exists we're gonna fire some code and now I want to delete that file and we do that by saying FS dots on link that is the method we use to delete a file so this time I want to specify that I want to delete the file which is in the docs folder and it's deletes me txt and then the second argument is a callback function again we can take in an error object if there is one we can check if there is down here if error then we're going to console dot log the error and also oops keep making this mistake let me just change that okay and also down here we want to say console dot log and we're going to say file deleted okay so now if this exists we're going to delete it if it doesn't exist we're not going to run the code so I'm gonna say node files and it's going to delete that over there but if I run it again we don't get an error or anything because it's not running this code so if I create it again new file delete me txt and try it again node files it's going to delete it for me okay cool so that's how simple it is to work with the file system in node.js now all of what I've shown you here works really well for small files like we have but if we're reading from and writing to really really large files then it becomes more efficient to use streams to read and write data to and fro files so let's just take a few minutes to talk about that alright then so we've seen how node can read data or files from a computer now but sometimes those files could be very very very large and therefore it would take a long time to read them and we could end up waiting awhile to do something with the data before it's even been fully read now to combat this we could use something known as streams so using streams we can start using the data before it's fully been read so streams work in a similar way to real live streams imagine we had some kind of huge water basin or a source of water somewhere and then also imagine we had a pool that needs filling up with water from that basin now one option would be to get a huge tank fill it up completely with the full amount of water we need to fill the pool and then deliver it to the pool and empty all of the water in it at once to fill it now that means that you have to wait a really long time while the tank fills up initially and then deliver it to the pool all at once now the other option would be to have a stream that delivers the water and that way it fills up the pool a little bit at a time but we can start using the pool with a bit of water in it almost straight away so the same logic applies with data so now imagine we have a huge large data source some kind of huge file and we want to read it we could wait until all of it's been read and then do something with it but that could take a long time or we could pass the data a bit at a time through a stream and this way small chunks of data are packaged up into what's known as a buffer and then sent down the stream every time the buffer fills so every time we get a new chunk of data from the buffer we can start using it now you get this in action when you're probably streaming something on Netflix or YouTube where little bits of data are sent to the browser a bit at a time so you can start watching straight away without having to wait for the whole video to load initially so that's the theory behind streams and buffers now let's see them in action all right then so there are a couple of different types of stream that I want to show you reach dreams and write streams now we read data via reach dreams and we write data via write streams pretty obvious right so I've already created this dream CAS file where I'm working from and I've required the FS module which we will be using to create these different streams I've also created another document blog three txt inside the docs folder and this time it contains a lot more content so it's a larger file than we worked with before it's not a huge file but it's definitely larger so we're going to create now a stream to first of all read from this file so how do we do that well I'm gonna say Const and then I'm gonna call this read stream call it what you will and this is equal to the FS module dot create read stream and this creates us II read stream now the first argument inside this method is gonna say where we want to read data from and where do we want to pass data from through the stream and we're gonna pass it from this blog 3 txt file so dot /to say the current directory then into the docs folder then we want blog 3 txt so that's the first argument and in fact we'll leave the second argument for now I'll come back to that shortly so down here what I'm gonna say is read stream dots on and then passing a first argument which is data I'll explain this in a second and a second argument which is a function and this function takes in a chunk of data so what's going on here well we've created the read stream we've set it up and we've told node where we're reading data from so it starts to read that data now this right here this dot on on our read stream this is an event listener so you know like in front in JavaScript where we might have a button and we listen to a click event it's similar to that but this time we're listening to a data event on this read stream and that is basically every time we receive a buffer of data from this stream remember I said the industry and we get small packages of data come to us at a time so that we can start using them straight are pretty much straight away so this is a data event meaning this is when we get a chunk of data that we can use from the stream and every time that we get a new chunk of data we fire this callback function and we get access to that chunk of data does that make sense okay so what I'm gonna do is unlock this to the console so console dot log and we'll say chunk and in fact above that I'm also going to log to the console a little message that says new chunk so we can see the glance where the new chunks are make sense okay so let me now save this and run it so node streams oops not in capitals node streams and press ENTER and now we can see we get these different buffers right here and every time we get one without putting new chunk this and then the buffer itself the package of data that we get every time so we're getting a bit at a time now again we'd like to see in a readable format so we could say dot two string right here if we wanted to like this and that would do what we want it to do if I run this again node streams and we can see all that now in string format and if we scroll up we should see the message new chunk somewhere if I scroll far enough what the chunks are quite large but let me just keep going and eventually we see one right here in new chunk okay now we could do this or we could pass in a second argument which is an option object right here and as a parameter inside this we could specify the encoding and set that to be utf-8 meaning it's going to encode this as it comes in and it will automatically be in a readable format these letters right here so now we no longer have to say to string so if I save this again and come to the bottom and run it again note streams it works the same way okay so that is a read stream now we can also create write streams where we write data to a file a bit at a time so to do that first of all we need to do something similar like this to create a right stream so I'm gonna say Const and I'm going to call this right stream and I'm going to set it equal to FS create right stream oops create right stream and then inside here we need to say what file we want to write to so let's write to a new file so I'll say dot forward slash then into the docs folder then blog four dot txt okay so now what I'm going to do inside here every time we get a chunk is write that chunk to the new file so I'm going to say write stream down here dots right and then pass in the chunk like so now I'm also going to write something else to it so write stream and then in here I'm going to pass in a string and I'll do an escape character first of all and n meaning we go to a new line in the file then I'm gonna say new chunk and then I'll do another new line as well after that okay alright so what this is doing is every time we get a new piece of data from the read stream we're going to take that bit of data and we're going to up so we need to say dot writes here we're going to write first of all this new chunk line then we're going to write the new chunk to that file as well so this is how we pass data down a stream a write stream we pass through a new chunk of data using the write method okay so let's save this now notice we don't have blog for txt just yet but if I run this file no streams then we should get it blog for right here and if we open this up we can see new chunk and when we get all the text and then if we scroll down a bit more we can see new chunk and more text and then new chunk more text etc so we now use this write stream to send a bit of data down it at a time to write to this new file so finally I want to show you something called a pipe which works well when we're passing data directly from a readable to a writable stream it's basically a much shorter way to write all of this stuff right here but it will essentially do the same thing but when we use a pipe it must be from a readable stream to a writable one so let's have a look at how this works I'm gonna comment all of that out and all I'm gonna do is a comment down here to say piping and then underneath I'm gonna say take the reed stream that we're reading data from and I want you to pipe whatever you read from the read stream into the write stream so what we're doing is basically opening up this read stream reading data and every time we get a chunk under the hood its piping that into the write streams of doing the same thing as what we're doing right here but this is much easier to write than all of this right so let me now delete blog 4 just to show you that this works and I'm gonna save it and run this file again node streams and you'll notice we see blog for now and it's written all of that content to blog for now there is also another kind of stream called a duplex stream which means we can read and write through it but that is a bit beyond the scope of this lesson so there my friends in this video we've seen quite a lot of the basics of node we've seen how to actually run code using node on our computer we've seen all about the global object and the different methods and properties available to us we've taken a look at the node module system to import and export things to and from different files we've seen the file system core module and also how to create streams for reading and writing large amounts of data now another core built in module is the HTTP module and that's used to create a server which is what is used to manage the backend of a website so we're going to talk about that a little bit more in the next lesson you
Info
Channel: The Net Ninja
Views: 165,595
Rating: undefined out of 5
Keywords: node.js, node, node js, node.js tutorial, node tutorial, node js tutorial, node crash course, node.js crash couse, node js crash course, crash course, tutorial, install node js, install, node.js introduction, what is node.js, what is node js, what is node, node vs deno, file system, node file system, node streams, streams, buffers, node global
Id: OIBIXYLJjsI
Channel Id: undefined
Length: 42min 44sec (2564 seconds)
Published: Mon Jun 15 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.