Node.js and NPM Tutorial: readFile & writeFile, Require Modules, and Install Packages

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey welcome back to the bootcamp series in this video we're going to learn about something called nodejs what in the world is node well imagine there was this environment where we could speak the javascript language but we weren't limited to just being inside a web browser doing web browserish things right so node is this environment where we write javascript but we can do sort of general purpose computer programming things like interact with the file system right we can read the contents of files on our hard drive we can create new files on our hard drive programmatically with node so with that in mind you can imagine that we can use node to automate all sorts of different tasks for us also node can not only make outgoing network requests but it can listen ongoing for incoming requests so you can imagine that we can use node to set up a web server big picture node essentially makes it possible to do anything with javascript but let's not get ahead of ourselves in this video we're not going to be setting up a server or any sort of advanced automation in this video in this video we just want to get node installed on our computer see how to run a little bit of node code and just the essentials to get up and running without further ado let's jump into that action okay so first we need to install node on our computer so you can just visit the official website it's nodejs.org towards the bottom of the home page you'll usually see two download links so the one on the left is the long term support version and the one on the right is the newest or latest version now if you're watching this video in the future the exact version numbers will be different but that really doesn't matter you can download either one if we were setting up a server instead of just installing node on our computer i'd probably recommend the long term support version but since we don't need the absolute best possible stability and we're just installing it on our personal computer right now you might as well go with the newest or latest version but either way you can't go wrong so right now go ahead and pause the video and download and install this file all of the default options are okay so you should be able to just click next next next okay now once you've completed the installation and you come back and resume this video we'll want to test to make sure that you installed it successfully so to do that we just want to jump into a command line now if you're already a bit experienced with computers and programming you'll know how to find your own command line but if you're new to this whole programming world this is one of the reasons i recommended the visual studio code as our text editor and that's because it has a built-in command line so in vs code you can just click the view menu and then choose the terminal so that's going to open up your command line at the bottom of vs code also there's a keyboard shortcut for this so on windows you can press ctrl j or on mac you can press command j and that will toggle and open and close the command line okay now if you click into the command line we just want to run this command node and then a space and then dash v if we press enter you hopefully should see some sort of version number right so it's going to tell you which version of node you have installed and again if you're watching this in the future your version number does not need to match mine as long as you see any sort of version number here you're good to go you have successfully installed node if instead you see something like command not found or unknown command you might just need to restart your computer or completely close out your text editor and reopen it but the question now is once we have node installed what can we do with it well check this out in the command line if we just run the command of node and nothing else just node and press enter well that enters us into this interactive node environment so now when we type commands here we're no longer typing operating system commands we're now in the world of node and we can think of this as just a place where we can type javascript almost similar to when we're in the console in our web browser so we could type 2 plus 2. press enter we get 4 or we could create a variable in memory say let my name equal string of text now we can access that again say my name it returns the value and this is just regular javascript so we could say my name and then all strings have a method of two upper case parentheses to call it you get the idea so this is just a javascript environment however up until this point in this bootcamp series we've been using javascript in a web browser and we've learned that you can select different content on the web page by using the document object however in node if we say document and press enter we see uncaught reference error document is not defined also in the web browser we know we can have an annoying alert pop-up by calling alert but in the world of node again that does not exist so we can think of node as sort of the javascript environment of the web browser but all of the things that are specifically related to the web browser have been stripped out and instead we have new functionality that's specific to node for example node can read files from our hard drive and create new files on our hard drive and node can not only make outgoing network requests but it can listen ongoing for incoming network requests so both the web browser and node both speak the javascript language but they each have their own unique super powers that the other doesn't have but the beautiful part is that the core of the javascript language itself that never changes and that's still available to us right so everything we've learned about objects or arrays or variables or scope or functions everything is still exactly the same here in node and this is great however we don't want to be limited to just typing in single commands one at a time here so to get out of this interactive node mode in the command line you can just press ctrl c twice on your keyboard or if i go back into node you can also exit this mode by typing dot exit press enter and that will also remove you from the interactive node mode okay but the point is instead of just running individual commands one by one like that we probably want to write a javascript file with as many lines of code as we want and then tell node to execute that file so let's try that right now i want you to create an empty folder somewhere on your computer so i'm just going to create a new folder on my desktop you could create it anywhere but i'll name it node test the name doesn't matter but then go ahead and open this folder in vs code okay so when you open an entire folder in vs code now in the left hand sidebar we can create a new file we can name it anything but i'll name it maybe test dot js so we could say let my favorite number equal 10 and then on a new line of code we could say console.log my favorite number maybe plus one just as a test right so we would expect to see 11 in the console so you can save this file the point is is you can write as much javascript as you want you can do very complex things in javascript that's just a quick example but now we would want node to actually run or execute this so in the command line again that's ctrl j or command j to open up or to toggle the command line you just say node and then a space and then you point towards the name of your file so i named mine test.js you actually don't even need to include the file extension so you can say dot js or you can just say the name of the file without the jet.js press enter cool and there we see console.log 11. at this point i want to show you a very important feature in node and that is importing or loading or requiring in a separate javascript file within the file we're currently in so for example let's imagine we want to have a function that triples any number you give it now yes we could write that in one line of code but imagine instead it was super complex and it required hundreds of lines of code and we didn't want to make this file messy instead we wanted to have a separate file where all of the logic for that triple function can live that way our main javascript file stays clean and organized so for example we could create a separate file in our folder you can name it anything but maybe i'll name it triple me dot js okay so in this file i would say function triple me parentheses currently brackets in the parentheses let's have one parameter to receive the incoming number and then inside the body of the function let's just return that incoming number asterisk or multiply by three okay now that's the function but then at the very bottom of this file below the end of our function we do want to say module dot exports equals whatever we want this file to export so we would just point towards our triple me function so triple me now we're not calling the function here so we don't want parentheses here we're not trying to execute it right here and there we're just exporting the function itself so that a different file can import this and use it whenever and wherever it sees fit so if we save this file now back in our main file up at the very top we can say triple me equals and then node has this function called require and in the parentheses you just point towards that file so we give it a string of text in node you can say dot slash to look in the current directory or folder that we're already in and then the file name so triple me you can include the dot js if you want to but you don't need to okay so now this variable this is going to be whatever that file exported which is the function so we can get rid of my favorite number and then in console.log we can just say right in here maybe call our triple me function and give it a value of 10. so if we save this and run it we would expect to see a value of 30. so down in our command line if we say node test perfect now in addition to importing our own files that we ourselves created we can also load in or import modules that exist in the core of node itself right sort of built-in features that node offers perhaps the most famous of these is something called file system and this is what lets node read files on our hard drive or create brand new files on our hard drive so on and so forth so to begin using this we can just say const fs for file system technically you can make up any variable name you want here but just so it makes sense you can say fs equals require and now instead of a path pointing towards a file in our folder we just say fs that's it node will know what this means fs is a built-in module in the core of node and now we have access to it within this file from this fs variable now you can learn more about the different modules that the core of node offers and the different functions that they all have by going to the node documentation so for example here i am on the node documentation for the fs module now reading through this documentation is not very exciting and unless you have a specific task in mind it's not very useful however let me walk you through a quick example so let's imagine we want to use the file system module to read the contents of a file in our folder and then slightly modify it and then output it in a brand new dynamically created file so here's an example let's create a brand new file really quick in our folder let's name it we could name it anything but maybe content dot txt okay now inside this new empty file let's say the sky is blue let's go ahead and save that now back in our test.js file imagine we want to use the node file system module to read the contents of our new txt file and then maybe wrap it in an html heading level one tag and then export that as a new file in our folder and perhaps we can name it index.html so here's how we can do that down here let's start using the fs variable or the fs module so fs and then we can look inside it with a dot and it has a function named read file when we call it inside these parentheses we want to give it three arguments so a comma b comma c for placeholders the first argument is the file that we want to read so let's just give it a string of text and point towards that we named it content.txt file so dot slash to look in the current directory and then just content dot txt okay the second argument so instead of this b placeholder this is the encoding type of the file so we can just give it a string of text and say utf-8 okay and then this third argument is a function that we want to run once node has actually successfully read the contents of this file right we don't know how long that's going to take it could take one millisecond or if the computer and hard drive is super slow maybe it takes a second or two we don't know but when it actually does complete only then will the function we have here actually run so instead of c let's say function parentheses curly brackets now in these parentheses we want to have two parameters we can make up any names for the parameters but just so it makes sense why don't we say e-r-r for error and the second one can be data okay inside the body of our function here let's say if there is an error throw the error so we can see it in the console if there is no error then what do we actually want to do well data is going to contain the contents of this file that we just read right that's what we named this second parameter so just as a quick test if we say console.log data give that a save and now if we run this in the command line down here node test awesome there we see the sky is blue so we were able to successfully read the contents of that file now let's practice writing and creating a brand new file so imagine we want to create a file in our folder called index.html and we just want to take the content of this file and maybe wrap it in a heading level one tag so to do that instead of console.log data here let's get rid of that and let's use the fs module again so fs dot and look inside it for a function named write file parentheses to call it and again we're going to give it three arguments so a comma b comma c the first argument is the name of the file that we want to create so string of text dot slash just in the current directory let's name it index dot html the second argument instead of this b placeholder is the string of text that we want to be in this new file so instead of a basic pair of quotes let's actually use back ticks so we can do something dynamic so let's just have a heading level one opening and closing tag and then in between them that's where we'd want the actual content that we read so that's just dollar sign curly brackets to do something dynamic and then say data okay and then this third argument again this is a function that will run only once this task of creating the file has actually completed so we can just say function parentheses currently brackets you can check for an error so we can include that as a parameter inside the body of the function we can say if there is an error throw it so we can read it in the console but if there is no error let's just log to the console and say file was successfully created okay let's save this and test it out so back in the command line let me open up my file explorer too so we can see if the file gets created if we say node test press enter we see cool file was successfully created and over in the file tree we see index.html that was programmatically created by node and if we open it up perfect we successfully read the contents of one file and then output it into this new file now if i jump back into our main test js file i do want to point out that fs or file system is just one of the many features built into the core of node so for example in the node documentation here we see file system but we also see events and http and path so on and so forth however i want to let you in on a little secret well it's not really a secret but i would say 95 times out of 100 in the real world there's really no need for you and i to manually research and use these core components of node i'm not saying we'll never need to do that but just that most of the time it's not necessary because instead we're usually just going to use a community created package that uses the right node code for us at the right moments let me explain what i mean so in our previous video we learned about react and we know that if we want to be able to automatically transpile our react jsx into traditional javascript we need node on our computer however you and i don't need to manually write all of the node code that reads the contents of one file and then creates a new file instead there's this industry standard package called webpack and you can see that just in the last week alone it's been downloaded over 12 million times or for a different example in the next chapter of this bootcamp series when we learn about servers we're not going to write all of the node code ourselves that listens for incoming connections so on and so forth instead we're just going to leverage this industry standard package named express and you can see just in the last week it has over 14 million downloads and for yet another example when it comes time for us to connect a database to our server again we're not going to write the code that micromanages the connection to a database instead we're just going to use a package such as this mongodb package if we want to use mongodb it has 2 million weekly downloads or perhaps we'd use this mysql package if we want to use a mysql database you get the idea depending on what we need to do there's probably already an industry standard package that does exactly that so yes the creators and authors of these packages need to research and write node code but oftentimes in the real world you and i really don't need to now yes there will be times when these packages don't do exactly what we need them to do and in those situations that's when you can go to the node documentation perform your own research on the task you need to do roll up your sleeves and make it happen but like i said before i would say nine times out of ten that's not necessary and these packages will do the trick for us so big picture what i'm trying to say is that learning node itself is not a bad idea it's just something that i wouldn't do preemptively when you run into a situation where you really need a custom solution maybe you can write the node code yourself anyways having said all of that at this point you might be wondering what is this website i'm looking at that has all of these different packages well this is a website called npm which stands for node package manager and what's cool is yes we can come to this website and search for packages and read about them but when we actually want to use and download a package we can just go to our command line because when we installed node on our computers it also installed a command called npm so right now i want you to do this with me in vs code in your command line go ahead and type in npm and then a space init and then a space dash y go ahead and press enter now what did that just do well first of all you only need to run that command when you're first starting a new project right so a new folder on your computer for each separate project we just run that command once in the beginning and it creates this file for us named package.json now this file is essentially a grocery list that keeps track of any packages and ingredients our project needs so for example if i go back to the npm website we're not going to install webpack or express or mongodb or any of those things in this video because this video should be relatively short and it's just about node and npm not about any of these actual packages but just for a quick example maybe we want to install this package called validator so you can give it a string of text and then you can ask is this string of text an email address and then it will return either true or false or you can give it a string of text and say is this text alphanumeric meaning does it only contain letters and numbers and no other strange characters and it will return either true or false so it's just a little helper or utility library but just for a quick example let's try to download it and install it into our project so we take note of its name it's validator so in our command line now that we've created our grocery list or our package.json file if we just say npm install and then the name of the package is validator push enter cool now that just did two things so first of all if you look in your package.json file down towards the bottom we see this dependencies property and it's going to keep a list of any packages we install so there's validator we just added that so that's the first thing that that command did but secondly you'll notice this new node modules folder and npm automatically went out onto the internet and downloaded any of the files that we need for that package okay so now the question becomes how do we actually use that package in our code so to test it out we can just go into our main test js file that we were working in earlier and up at the very top first we want to import or require in that package so we can just say const you could name it anything but let's say validator equals require again we give require a string of text and you just include the npm package name so validator and that's all we need to do node is smart enough to know where to look it will look within our node modules folder the downloaded files and it will pull in that package or that module so now just as a quick test down here we could try to use that package we can say console.log and then let's log out validator dot is email so we're calling this method and if you give it a string of text if you say john this should return a value of false right this is not a valid email address so if we save this and then run this file so in our command line node test or whatever you named your file cool there we see false however if we change this to john at test.com so this is a valid email address hit save run it again node test now we see true so it's that easy to use npm to download a package and then use it in your node file really quick i do want to show you why the package.json file is so important and so valuable so for example if i deleted my node modules folder right that's the folder that contains all of the downloaded files for the packages we want so if i delete that it's not a big deal because we still have our package.json file which lists out any and all dependencies now yes we only have the one a validator but imagine if we had 50 or 100 different dependencies for a project well as long as you still have your package.json file you can just say in the command line npm install and that's it you don't have to hit space and then list out a package name just npm install push enter we'll look at your package.json dependencies and go out and automatically download all of them now for some reason i'm not seeing the node modules folder recreated here i think that's just a vs code bug so if i click this reload icon here cool yet you can see there's the node modules folder created again for us by the npm command so just that one npm install will go out and re-download any and all dependencies you have no matter how many there are and now we can run our code again node test and it still works it is still able to pull in that downloaded validator package the reason i wanted to show you that is because in the industry oftentimes when a co-worker sends you a git repo or the files for a project there will not be a node modules folder to start out with instead though as long as they give you a package.json file that's okay you just run the npm install command and then you will have all of the files you need anyways that brings us to the end of the technical aspect of this video so where do we go from here well now that we know the very basics of node and we have it installed on our computers let's get back to what we wanted to do at the very end of our previous video so remember we were working with react and the jsx syntax and we needed some sort of automated way to transpile the jsx into traditional javascript well we can absolutely use node to do that and that's exactly what we're going to set up in our next video we're going to use an industry standard package named webpack should be a lot of fun if you're enjoying this bootcamp series so far as always i'd appreciate it if you share the link with your friends and family take care and i'll see you in the next [Music] one you
Info
Channel: LearnWebCode
Views: 9,551
Rating: 4.9795918 out of 5
Keywords:
Id: hl3IbJuzg_s
Channel Id: undefined
Length: 29min 18sec (1758 seconds)
Published: Mon Sep 21 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.