Introduction To Nodejs - File System - A beginner's guide

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
yeah welcome to this tutorial it is all about noes today yeah we'll be talking about NOS for the next few series of videos that I'm going to be making and it's going to be a totally beginner friendly video um it's going to be a command line application so we will not be needing uh so much of extra weight for somebody that just starting out the reason for creating this is to help people starting out in no so people without programming knowledge to be able to start out in nodejs without much stress so what we'll be doing is we'll be building a crow application but it will be a commandline application you know with no interface but it will help you see the full power of nodejs the beautiful thing about JavaScript now is that it's not just the browser that understands it the computers Now understand it now it's different from when we use JavaScript for only frontend applications now we can use JavaScript for backend applications through the help of nodejs and the gole vs engine and I really hope you enjoy this video as we get started for you to get started you will need to download the nodejs um letters and stable one that is 18.1 4.0 it is recommended for most ERS but you can get the 19.6 which is the current one now while this is the current version as at the time when I'm producing this video it might not be the same as at when you will be watching this video or taking the tutorial but it doesn't matter always go for those ones recommended for the users and that is usually on the left it's usually written there so you don't have anything to be confused about so after downloading it and installing it it is pretty straightforward then you want to check on if everything was done correctly so what you can do is to check for the version if it return returns a version number then that means what you installed is correct um something else to noce when you install node it also installs npm npm is node package manager as we continue you will see how and why it is important but generally it helps us to add extra codes or external codes that are not written by us to our own code in order to make us write faster and more efficiently so to check uh if node was installed properly or correctly just type node and version node version like this hit enter oh sorry just node and um double um hyph there version and it should return a version number like this so for me I do not have the latest I am using version 16.1 5.1 and that is totally fine it doesn't really matter uh you just need to have node installed then to also check for npm just do npm hying you can do double hying version or you could just do hyphen V this way hit enter and it returns a version number once you can return a version number then that means everything is properly installed now you can actually check out noj in the terminal to see the power of noj and you notice that as soon as we hit into node so just do node enter it welcomes us into the version of node and then you could manipulate JavaScript from here for example you could do something like 5 + 5 and that should give us an answer the answer is already coming up when hit enter gives you 10 so stuff like that but we we will not be working just here in the terminal we write code that will help us to use the terminal that's what we want to do and I'll be demonstrating to you what we will achieve by the end of this uh this tutorial so let me bring this in um this a demo code I have written uh I'll just demonstrate based on what we'll be doing here so one thing that I'll will be doing first of all let me let me get rid of the db. Jon it will be automatically created so let me delete that okay good so one thing that we will do the very first thing that we do will be to add data so we will have to run the add data file so to run a file we just need to do node name of that data you could add the extension or not but that's totally fine H enter it asks for name and you enter name Sam is fine you ask for phone number you put whatever your number is you ask for adult so the adult has multiple Choice uh options so you just pick the one you want so Sam is an adult so hit enter and it is saved yeah notice that it creates the db. Json file that wasn't there that part of the things you'll be learning you'll be learning how to manipulate files and then you learn a few other things like using the terminal uh using modules and all that now after adding data something else we can do is to retrieve the data so for us to retrieve data the code is written in the retrieve data file sorry retrieve data.js file so we just need to do node retrieve yeah retrieve data hit enter it returns this data I just entered notice some and the GI entered all right now after this what next what next is to update the file so let's update we do knowde update file node updates data sorry hit enter first thing it does is always to return for us the data that is already existing now what you want to do is passing this data and it will retrieve this data for us sorry passing the ID and it retrieves this data for us so you copy this paste it here and hit enter now it has retrieved the data for us and now it's asking us what is your name so what we want to do here is to update what is already there and what is already there is s so I want to change that to a hit enter I do not want to change the phone number so if I hit enter it will keep the initial value so I hit enter now for the adult I could change it to um n which means no it's not an adult or it's a minor please enter it's updated now if you decide to retrieve this data again you should see the updated data and now we have a bar instead of Sam and we're having a minor here instead of an adult beautiful right finally what we can do is to delete data and to do that we use the remove data file so we do node remove sorry remove data yeah hit enter this is the only data here we want to remove it and so we copy the ID paste it hit enter and it tells us deleted now how can we be sure that this data has been deleted check the db. Jon file I notice that we now have just an empty array unlike what we would have had if we had entered a data now just to confirm what we have done just to confirm what we have done control K to clear the terminal now let's create a new data hit enter uh it's showing an empty array because there's nothing here that's just what we have here but that's fine we add inju what's inu's phone number you just put some Bri and that's fine that's the phone number and then is here an adult yes it's an adult hit enter and notice that how quickly it Updates this file and we now have another code inside of here sorry another data inside of here something that you didn't see but was working on underneath is the DB file check this checks if the DB file exists now this is necessary for the update file and the delete file yes two of them notice that will call a function here once there is no database no file all what happens there is it do not run you do not even try to run the code at all not to talk about running and returning errors so this is important in order to save time and to save um resources generally and to make our code more robust so this is what we'll be building in this tutorial and this is the first one I'm really happy and I look forward to seeing you in the next video we'll be talking about a whole lot now a good thing I would I would could do is to share with you the list of things we are going to be learning so we've already done the introduction and the installation of node and npm so what we are going to be doing in the next video is going to be how to set up projects and uh how to install dependencies after that we move to uh how to create a new file from the terminal and maybe we also take take up how to to check if a file exists after that we should take the next two which is how to query database and how to retrieve data then add data should be a video of his own or a tutorial of his own uh how to delete sorry how to edit data should also be a video of his own and I think how to delete that should also be a video of it own either ways we have a lot to learn and I look forward to having all of you uh leave comments about what you learn and um how you intend to grow I will also leave some more tutorials that you can take after this in order to grow your node jsq so I'll see you in the next video catch you hey it's the second video for this tutorial series and I'm really excited about it now we are taking this as gradual as possible and so last tutorial the last video I was able to teach you uh how you can install nodejs and npm so what we are going to be doing in this video is to set up our project and install the necessary dependencies so for us to start uh navigate to somewhere inside your computer that you like your code to be so I would like my own to be inside of document you can use a terminal uh I use my terminal um on Mark you can use yours on Windows or wherever that you have them the commands are similar so CD into documents that's how we navigate CD means change directory so now I'm a document folder I will create a folder known as um nodejs crud something like that nodejs Crow so the command is make the IR and name of the folder not JS CLI cro think this makes more sense hit enter and the file has been created just to confirm that we already have the file just do LS hit enter and you will see it here so you should also check your own out clear it with crol K control K clears your terminal so what we want to do next is to navigate into the folder that we just created so you can do a CD into it CD into nodejs underscore CLI underscore cro hit enter and we're inside of this folder now now we could choose to work inside of this folder from the terminal here but I would love to work inside of the uh folder but using vs code vs code is um is an editor that helps us to write code uh it provides a terminal for us to use as well as a place for us to write code so having everything in the same place is easier and uh it's fun for me it's more interactive it's it makes sense so I will just open this folder in vs code you you could also check out vs code on um on the internet and just download yours so for me to do that I just the code space um period like this hit enter and it opens up for me it opens the project in an editor like this yeah that's it so is that beautiful and I could just open this folder in a terminal as time goes on so for me to open it in a terminal I could just do the control shift um back tips and just like that we have the terminal open like this beautiful so whatever we want to do now we can do it from here so first thing we've done is to create a folder so next thing is to initialize the product uh sorry the project so for you to initialize the project you do npm in it so here in the inside of the folder in the terminal you do npm init I hit enter now that will start bringing up for you some prompts to maybe filling names and other stuff you could fill in that but you could just hit enter until you get to the last one and it will creates a file for you that is the package dojason file and here you have it the package.json file beautiful that's awesome now before we continue we need to add a line here and that will be type type module the reason for adding this is because we are going to be working with the latest or a newer type of JavaScript which is the es6 JavaScript uh we use it to import module so if you don't have this line here in package in the package.json it's would not work as you expect but that's that's by by the way now with this we are now ready to install dependencies now what are dependencies you could also call these packages or modules these are external codes codes written by some other people in order to help us write code faster so this code uh sorry these programmers have taken their time to write this code and give it to us so that we do not have to rewrite it there's no point rewriting a code that has already been written except it's really really really necessary we'll be we'll be using two of those dependencies one is The Inquirer The Inquirer helps us to collect or prompt users to give us input from the command line and the second one is the uid uid it helps us to generate unique identifiers for each of the data that will be adding to our database to install a dependency you just need npm by the way npm that's the node packet manager helps us to install all these kind of external codes so they all leave on the website there so you could check check check out the npm website I'll try to put it down there in the description so what you need is npm install and then the package name package name so if we are going to install um uu ID for example what you need is npm install uu ID now mpm also gives us the liberty to install more than one package at a time so all you need to do is to um separate each package from the other using a space so if I'm going to install you ID and install inquir I just need to give a space like this Inquirer like this and that is it you'll be able to install this to something else you need to know is that you don't need to spell the install in full you could just use an I like this and so you can install uu ID and inquire at the same time so hit enter and it starts installing now when it's done you will see these names added as dependencies here beautiful it's done installing and here we have the dependencies these are the two dependencies we have just installed and if you look here in the list of um files and folders here you will notice that we now have a new folder no that node modules this folder contains all the bunch of external files that we can add but we do not really need to look into this we don't need it no no we don't need it we just need to know that this code behaves in this way or the other way and then forget about it the package uh lock Json we also don't need to look into that but if you feel like you could look into it there is really nothing you want to do here it is just part of the settings for our project and that completes the setup of our project we are now ready to start creating files and doing some other uh some other things here so uh the first thing we we might want to do is to create files that we will be working with in this tutorial we will working with a bunch of files but how do we create these files Now to create file um for Mac you just use touch the file name and it creates the file um if you're using Windows you need Echo with a DOT and a carrat sorry a greater than sign and then the file name stuff like that you could check that out like npm we also have the liberty of creating more than one file at a time and all you need to do is separate each file with a space so which files are we going to be needing in this tutorial let's start listing them out let's do touch like this yeah what is the first file the first file is query DB this will help us to um query the DB get uh data back and then run every of the other functions that we will be creating in other files as we continue you'll learn more about this the next file we want to create is the DB file check that helps us to check if uh the DB file exist JS please Ure that we are adding the JS extension JS like that yeah DB file check we check if the file is there if it's not there it will terminate the next one is the add data.js followed by retrieve data.js spelling not that correctly okay then update update data TS yeah after update data you now have the remove remove data.js now the rest of the file is self-explanatory and those are the files we need 1 2 3 4 five six seven I think files that is what we need now once you hit enter these files will to be created immediately now notice that these files are not here now so we just hit enter and all these files are created in one go you see how fast it is it's faster than trying to um hit here to create a new file and typing in the name and all that so in just one command we are able to create all these files these files are empty yes but we'll be filling them out from the next tutorial or the next video in this series catch you all right well welcome to the third video in this series so we've been able to install node and npm we've been able to set up our projects in the last video we saw how to install dependencies and we created files that are necessary for this project so we want to begin by um writing the code for the DB file check where we'll be looking at how to check if a file exists we want to check if the db. Json file exists if it exists then nothing happens but if it doesn't exist then the code has to be terminated but let's begin by checking how do we check now I told you we'll be learning how to manipulate files nodejs provides us with an inbu module called file system for us to use this file system we just need to import it so what we need to do is import FS that is short for file system from f yes this will be in quote so put this in quot and that is it come down here and check let's check for the uh what's the name the DB Json file now file system provides us with a method known as um exist sync exist sync so let's type it out exist sync exist sync like so now any file you pass into this will will be checked and you see if it exists or not so here we are passing in the db. Json file so let's do this db. Json file now how do we get an output just to be sure if it is true or not let's see uh we could do an if if statement if so if it's a conditional statement that we could use to check if something is true or false and then do some other stuff so the condition has to go inside of this bracket and then whatever want to happen if it is true or false depending on what want it to be we go into the braces so we we move this into this brackets now if this returns through let's log to the console we want this to show on the console console dolog file exists so we just type file exists now this this is all you really need to check if a file exists now to check if this is working let's run the file by saying node DB file check no DB file check we hit now it doesn't return any answer or any response but what happens if we put in a file that exists for example let's do the add data.js file we save it now let's run this file again you hit enter and it tells us file exist now this is this is because we have the ad do ad data.js file but for the um db. Json file we do not have it so what we want to do here is to check if this file does doesn't exist now if the file doesn't exist we want to return um an output or maybe just terminate the process now how do you check if a file doesn't exist what we will need to do is invert whatsoever statement that we are putting here for us to invert this we need to put a h an exclamation sign here so whatsoever is here will be inverted so this time around we we will say file does not exist now if we save this we should get no output because add data.js file exist so this and there is no output now let's change what we have here to db. Json again save it now output it output node js sorry node DB file check hit enter and it tells us that file does does not exist beautiful that is what we are looking to do so how do we intend to use this code in other files we've we've actually done what we really want to do and that is to tell a person who probably wants to update or maybe remove data that hey the file doesn't even exist so you can't do that but how do we get to use this code in other files it is just like when we say that we'll be using external codes that is code written by other people in our own code for us to use such code for example the fs that is a file system we have to import it now we will only able to import this because they have exported it so for us to be able to use this code in other files we need to export it now how do we export it we use the export command so let's clear this and say export we put default this default keyword is important because it is the first file that we are going to be expecting it is expected that the first file has that default um the default keyword all right now we we can make it an as as an asynchronous function if you want it is not actually necessary then we now use the function keyword function so a function basically packages code and then when you call the function it executes whatsoever it's inside that function will not give function a name name we give you the same name that our file has and that is DB file check make sure you open and close braces like this that is the regular braces and then open and close call braces this is where we will be putting in our code and so let's paste the code that I copied inside of here we can pass in any data that we want just in case of future you'll see where we'll be passing in data um from these braces that is why the braces are there now if you don't pass in any brace sorry if you don't pass in any data nothing would happen so we are saying that file does not exist here but after this we want to make sure that this code terminates so we will call on a function known as exit now exit is also an imported uh function or method from a module called process so it was automatically imported for me because I have all that set up in the VSS code so as soon as I hit the exit and put it down there it Imports it for me I could add one because that's that's the code that is used to terminate processes and that is all you need in order for you to check if a file does not exist that is the db. Json file and then terminate the code as necessary that's all nothing else now we'll start using this code or we'll call on this function in the future not now we'll call on this function when we will be building our update data uh function and the remove data function but right now this is what we have and I see you in the next tutorial where we'll be talking about how to query database and retrieve data see you then yo this is the fourth video in this series and we'll be looking at how to retrieve data and Beyond retrieving data we'll also be looking at um how we could set up function that would help us to execute other codes because these um codes are interrelated to each other there's a whole lot we are going to be learning so let's Jump Right In so how do we retrieve data we are able to retrieve data from a particular file if we are able to read that file so in other words what you want to do in this video is to read files so how do we read files remember that we don't have we do not have the db. Json file right so we'll still try to read the file just to show you how it behaves what happens when we do that so I will first import FS from fs and then FS provides us with a um a method known as read file read file in the r file takes in the the file name and then a call back function that either throws an error or Returns the data that exists inside that file so the file we want to look at is db. Json db. Json uh and then it takes a function a call back function so let's create that function here it has no name and then inside of here it takes in two parameters that is the error and the data so the error represents whatsoever error that is encountered when trying to read the file and then the data represents whatsoever we get after reading the file successfully so what we will say here is if error exists if error is there let's log to the console some of these things I'm doing you already know them we've see them in previous videos so it shouldn't be so difficult um I hope you're able to follow so we Lo to the on to saying something went wrong went wrong and then show the error that we got however yeah we could also exit this place we just exit as usual just exit just as we exited the other time we use one as as usual all right then assuming that everything goes well let's log the data to the console so we just putting data here and that is it this is all you really need to read a file and we're trying to read the db. Json file so what will it tell us when we try to run the file so let's do node query DB what happens hit enter and it tells us that something went wrong what exactly went wrong when we look closely at the error here it's saying that no such file or directory that means that this file does not exist let's try reading a file that exist and has something in it and that would be the DB file check DB file check let's just be sure we spell that correctly DB file check okay I think that's correct you save that and then you run this again hit it and what does it tell us D file check does not okay we're using using a wrong extension it should bejs not Json so save it again all right let's clear the terminal run it again and hit enter now it returns our data because the file exist but notice that it returns it as a buffer let's let's zoom in on this it returns it as a buffer with codes yeah a very long code so what do we do about this now let's go back to our code and then let's make this to be readable for for us to make it readable we need to convert this to a string so we do dot to string do to string don't forget about the closing braces save it and let's try reading that file again so control K to clear read the file again hit enter and boom we have everything that is written in that file isn't this awesome this is everything we have in thata and so we could choose to manipulate this just as we wish it's a string at this point beautiful now if you recall we said that we want to do more than just retrieve file and show file in this particular file sorry retrieve data and show data in this particular file we want to be able to take in uh functions from other files and run them through this particular function so that means first we need to export this function now I I made a mistake in the other file when we're creating the DB file check I said the default keyword is um necessary way is that I said default keyword is necessary when you're exporting the file now you're not actually exporting the file I mean exporting the function not exporting the file we could have multiple functions in this file as we will see very soon but the only one can have the default keyword because it's like the base function or the default function we just have that at the back of our mind mind so back to this what you want to do is first export the function taking a parameter or an argument and then write a code that would handle all those scenario but let's begin by exporting so want to convert this to uh something that will be exported so let's let me cut and hold on to that code and then export export it will be default it will be a synr uh this is very necessary uh especially for when you'll be reading files that are from remote locations that are not in your computer so it would take some times for for you to get the data back so that you don't run into timeout or stuff like that so try to ensure that your function is a synchronous and um the file system manipulations are also asynchronous all right so as Sy function you hit enter it auto creates the function for me and I'll be naming this function the same name of the file and that's query DB awesome now it will be taking an argument and want that to be the external function also all right it's getting a little longer so let's reduce the font I hope you can see that or maybe let me let me just drag this out and keep the font bigger yes all right just so that I can see everything properly now let's paste back this function here and we'll try calling it from another file where we actually retrieve data and that is the retrieve data.js file so first of all this file will this function will no longer work in this file because we are not calling it here in this file so just to test that out control clear run the file again and you get no output for this file sorry for this function to work we need to to call it somewhere now we could call it here like this and that should work call this here hit and we get our output right but since we want this file to do a lot of work it might start to interfere with other files when we start passing in the functions from other files into this function so what we want to do is to ensure that we are retrieving the file when we're supposed to retrieve it and we are using the data when we're supposed to use it just to separate concerns and also make our our project very modular easy to read we use another file to retrieve the data so we will now call this function in another file that is the retrieve data file so just the same way that we imported the fs module we also import the function that's the query DB function from the query db. JS file so let's do that import query DB all right from this make sure it has the extension. JS here all right and all we need to do is just to call the function query DB here and close that bracket save it and then let's call the function here we've cleared here all right let's now just to be clear when we call this it gives us no output now let's call the retrieve data function retrieve data file sorry hit and we have the output awesome everything is working perfectly now we'll come back to test this file again just to be sure everything is working fine after we finish building out the query DB file just to be sure so what do we want to happen here now this external function sometimes might need to be run only only after we've been able to retrieve data for example when we are working with the remove data file or the update data file we need to have retrieved the data before working on those file however if we working with the ad data file and there is no file that ad data file will create the file that is the db. Json file all right and so we will not need to have retrieved Data before running that file so in order to make sure that all the scenarios work properly we write rewrite all this code that we have here just to make sure everything is clear so let's clear this all right and then we'll start with the try and catch block the try and catch block will help us to catch um catch errors easily and then all our code that we really want to try out go into the try block cool so the tri block will just log the error to the console so log to the console and see something went wrong yes and then we just add the error what went wrong that is it all right all right now back into the triy block this is where everything actually lives the first thing we want to do here is to create a variable where we'll be keeping the uh data that will be getting from inside of the db. Json file all right so we we use a let let info equal to empty braces like this all right um this is a square bracket okay now the first thing is to check if the file exists so let's do an if statement it's going to be an if else so if else like this and what's the condition FS do exis sync we I want to check if the DB dojon file exist all right now if this file exists then we canot read the file so you put await FS dot read file read file remember it takes in two uh argument and the first one is the file that is being read get this off all right the file that is been read that is a DB dojon file and then the function the Callback function that has no name all right the cover function also takes in two argument and that is the error and data now if error so if for example error um occurs we want to make sure that we terminate the process so if there's error all right if there's error we'll log to the console and say reading file field we can add the error by the side for context all right now if there is no error we want to we want to process the data so for us to process the data we need to convert it to string and then convert it to um the original format that it was we are expecting that the db. Json data would be in um arrays and it would be it would be arrays of objects object of every data that we passed in so by passing it through the Json pass it will help us to convert it back to the regular array remember we first of all converted it to string from buffer to string before we'll be converting it to what it was before and it's going to be an array so let's let's get it back first thing we want to do is data dot to string remember to string now this converts it to a string but we want to take it back to what it really was before uh it was made a string and it was an array so we're converting it back to an array using json. pass and then we put this inside of here beautiful so we now have an array if the file was existing now that I have this we can now save what we have here in the info the info variable and that is awesome so what is next at this point at this point we want to check if an exal function was passed in and there is really no error so if an external function was passed in and there is no error then it will continue by running this code so we want to check if external er sorry external function and check that there is no error so the double and is saying that these two conditions must be true for this block to run now if these two conditions are true then we will now run this function this function would be needing the info variable that we have here basically what this is saying is while running this function you pass in this database data into the function so that the function can use and after it's done using it it's Returns the updated function back to the database make sense now there will be one case when uh we want to make sure that we we terminate um we terminate any process after an error or after a block is done so let's use the okay um okay this is not really necessary here we can just stay like this yeah and that's fine but we use a return just just to be sure we just use a return same thing for here we could use a return all right then how about in the other case so let's say we have a function um the add data function especially it's it is here and there is there is no no file but we want to add data now at the point of adding data it is okay not to have a file because the add data file will create the file so we want to do if the external function exists at this point in the else um sorry in the else blog it already means that the file doesn't exist so if that file doesn't exist and the external function exists we just run the external function and return here like that is it so either ways we are getting what we asked for we think we need to remove this exit from here um that wasn't necessary all right so let's save that just to be sure that the retrieve data file still works so let's clear this do the retrieve data hit it it it returns nothing because we do not have this db. Json file but let's be clear um DB file check JS save it okay we also need to copy paste it here we just want to be sure that we are not breaking anything that we have set up before so let's save this and run this again hit it uh we have an error somewhere undefined one so where is this jason. pass so undefined one so where are we having an error this data to string oh oh oh oh oh oh yeah we we can't actually pass what we have here we can't actually let's let's um let's Commander out we can't pass that um it's it's not an array yet what we have there is just a bunch of text um we just have a bunch of text but let's be sure that we are getting the right thing here so let's log to the console what we are getting log do data dot to string save and let's run this again beautiful everything works fine so what was happening before was you know we are expecting that what we be passing into the database would be an array so because we expecting that it would be an array we have decided to pass it and as at the point of passing it we are doing a wrong conversion which doesn't exist but as we continue you see why this code um is correct so we can we can just get this away from here and then we'll log the info to the console we just want to be seeing what we have in the database at every point so for every time we call it we want to have it all right so let's let's clear this everything works perfectly from what we have done so far but I'll give you a run through again for what we are doing here so what we are doing here is we are retrieving data from the database which at at the moment really doesn't exist but but we are we have tested using the DB file check and we see that it's working when when we start working properly on adding data which is actually the next video you will see how we we create that file how we add to the file and how we retrieve it and you see everything makes more sense we want to change this back to db. Json because that's what we'll be working with uh feel free to create a db. Json file and um put in a bunch of code and see what what comes out of it you know what I think we'll just do that right away just to be sure dbj in file we we are creating that enter and we need an array of um anything so an array of name Sam yeah some let's save that now let's try to retrieve this file so all right sorry let's try to retrieve this file so H this and then we have an error node retrieve yeah supposed to be retrieve data retrieve data so hit enter and then notice that we have exactly what we have here in this place so to show you that what we did here works perfectly assuming we had a DB jent file makes sense all right let me walk you through what we have done here again the first thing we did was to export the function that we are creating that is a query D sorry query DB uh function we also took in an external function which will create subsequently and then we we sorry all right and then we began by creating a tri catch block recall that we say that the TR catch blocks help us to catch error at this point so if everything inside here fails then we can catch the error here all right now inside the cat block sorry inside the tri block we began by creating a variable this info variable is to hold the data that we will be retrieving in a moment then we now check does this DB dojon file exist now if it doesn't exist for a file like the add data file it will still run down here however a file like the update data and the remove data would get to this end because the DB file check would have terminated the process now if it exists we retrieve the data or we try to retrieve the data now if there's an error we return this error and return and the process stops if there is no error if there is no error then sorry if there is no error we get our data back and we convert it back to what is supposed to be and that is an array now after that we now check if the external function exists and there is no error then we will execute if not we come down here and check now let's assume that the file isn't there but we have the external function what do we do we execute and that's is all that is happening in this code we have gotten this right and we will move to the add data file in the next tutorial or in the next video see you in that one all right it is time for us to work on the ad data F what we want to do at this point is to collect data from or collect input from the terminal then gather it make it into an object and then add it to the database and add it to the database uh in this place we'll be using the inquiry um dependency we'll be using The UU ID dependency we'll be creating new file we'll be overwriting file there's a whole lot that we'll be doing in this um this file so I'm ready once you're ready all right so the first thing we want to do here is to import everything we need we'll be needing the fs the file system module we'll be needing The UU ID module we'll be needing we'll be needing the inquir uh inquire module and then um of course we'll be needing the query DB module you will see why all these are necessary in a bit and I will just paste them in all right so uh this shouldn't look um so different this is The Inquirer this is the file system now just for here we are changing the name of the uid V4 into V4 sorry into UI so we are changing V4 and using U ID V4 instead um just a sort of convention you don't have to be wor about that then we are importing the query DB from query db. JS and that is all so we just get started um by creating the function um that will be using for this file you really don't have to export this because we are not using it in other file but um I love I love to export the first file just in case I ever need to use it in the future so I just export default not the first file the first function I'll just mix that up I think function uh add data it doesn't need any parameter so we just okay yeah it takes in the info parameter you you recall that the external function that is passed into the query DB here will take in if a an info variable which is the data that is gotten from the database so yes it takes in the info um the info argument or variable all right like in the query DB the first thing I want to do here is to do the TR card block boom just same thing and what do we want to do here we just want to tell them that something went wrong and because something went wrong um there's an error so we just p in um some code we we've already done this before for so we can just paste it in all right cool now we're getting closer to the interesting part I know you're wondering how do we get to fetch data from uh the terminal so that's what we want to do now we'll be using the Inquirer module so what we do is to is to call on The Inquirer this supposed to be an an asynchronous function so uh because it's an asynchronous function we're supposed to have an await in the front here await all right now The Inquirer has a method called prompt prompt this takes the list of questions that uh we want to ask users it also takes in the type of uh the type of input we are looking out for uh it takes some other things each each object each object of question can give a message a type a name it could give a default value they could give a maybe the list or choices that they expect the user to choose from and stuff like that for our case we just need three and that is the name the phone number and the age just telling us if this person is an adult or a minor you know stuff like that this will help us to use some of those properties so it's you open a and close bracket and inside here you open an um a square bracket like this so that we'll be able to make an array of OB so just hit enter so that it opens so what's the first thing I want to make there is the name now for the name the type would be of course type of string right yes type of of string but here we call it input so input is just fine then the name so which name do you want to use and store the data so name name will be fine for me just name then for the message what do we want to tell the user want to ask them to enter their name so please enter your name like this right let me just format that so that it falls improperly now we've done it for one and that is for the name we need another one for phone number so we just change this should be a number then phone then we say please enter your number that's fine then we will do another one this one now says H stuff like that um this would be lists like there'll be list of options and you say please uh um are you an adult are you an adult so we just need yes or no for for this so we we take the choices this time around choices beautiful and it will take um an array of objects now inside the array we have the name and the value so the name would be uh the name what we want to store when a value is chosen so the name can be the value if the name is the same thing as the value then you don't need to put in the two of them in fact all you need are two strings let me demonstrate that so if um the name and the string sorry if the name and um the value are different that's what we are doing now so we just open and then we'll put it will be an array of options so so the option name could be something like adults this should be a string adults and then the value would be something like yes why just yes then if the person is a minor so name would be minor and value value will be no no I am not I think I'm mixing all this up um we are supposed to actually change it this other way the name is what the um is what the user will see in the in the terminal and the value is what will be submitted or stored as uh as the Val as value get in the database so what we would do is let's rewrite this and so name that is what the user will see in the data sorry in the terminal is y and the value the value would be adult just copy and paste that change this to n which means no and change this to value of minor yes and that is it this is what we are looking for awesome awesome so we are not missing anything okay just the comma here now we want to store all this in a variable and that variable is uh answers we can use a con since this will not change after we f it so equal to await this all right just to keep everywhere clean all right now with this we can prompt the user for inputs and they give us input now what do we do next we need to organize this into an object each value we've gotten we need to to put it into an object and then now put it into the info um info array that we got from the database all right so coming down below here let's set up a variable called Data now in the data we want to have something like name name would be answers now this answers will be an object already right so answers do name the phone number would be answer DOT phone number think what do we save this as here the name okay name is phone not phone number so we just use phone here I think we can also change this back to phone okay then if last one is adults so answer do adult sorry H this should be H sorry okay AG let's just make sure that all this are in CS they well capitalized okay so now we we've created an object we now want to add this object to whatsoever we had in the info so if coming from the query DB here if the info is still empty it will be an empty array however if it already has data inside it will be an array of objects so what we just want to do here is to add whatsoever we have here in the data into the info so it becomes info. push we are pushing this data into this so push is if um is a method that available for arrays they are used to add new data or new information new stuff into an array so we've achieved the first step the next step for us is to check if the file exists now if that file exists that is the database file then we will just add this information we use this information to over write whatsoever we have already in the database now you start seeing why it's important that we first of all get this data from the database because we are going to overwrite it so when we are overwriting it we are overwriting it with both the old data and the new data that has just been added so let's check the first thing here is check it's it's going to be an if um if else statement so check if the file exists and we use exit sync passing the file and that is DB sorry db. Json this has to be a string now if it exists if it exists we will call it function which we are here to create and that is um add details so what this function will do or when we when we create it is to take in this data and overwrite whatsoever we already have in the database with it now but assuming that this file doesn't exist yet we need to create it and so to create it we use the append method so we go into the L block because we know that the file doesn't exist and let's create the file to create the file we do fs. append file it takes in three parameters the first one is the db. Json that is the name of the file like this the second one is the content what you want to pass into it something to notice you can only pass in a string so if you're passing anything into a file that you want to write into you need to make sure it's a string you have to convert it to a string which is also the same reason why we have to convert it back to the original format when we retrieve it now the last thing is um like a call function to uh check if there's error and if there's no error it returns a message so just function it has no name inside here we have error and now we say if error happen if error log to the console and say something like file creation or let's do creating file unsuccessful all right if it was successful then we want to go ahead I want to go ahead and first of all log to the console and say that file was created so we can just do DB do. Json file created [Music] successfully now after this we can now call on this same add details function so either ways we are calling on the add details function and that is it for this side for us to now we missed something please coming up here we need to add an ID which is what we use to locate each of this data that we're adding so we'll come to this place and just call The UU ID function and that is all we really need here once we call this function remember to make this a Comm instead of uh semicolon once we call this here it knows to generate and leave us here with a unique ID all right now that is it for this next thing is to create the add uh details function and we just need to do a create yeah and add details like this this one will take in um the info parameter and that is it all right we'll make it ASN as synchronous too make it as synchronous and when we jump right into it what all we are really doing here is to overwrite the file that we just created or the existing file with what we now have in the info variable so to override the file with a new data what we need to do is do our sing sorry our weit fs. write file now for a moment let me explain that the pen file and the right file are similar and they are different they are different in that the append file can create file both the sorry they are the same in that the pen file and the right file can create files if they are not existing however they are different because their pen file do not override the data in a file they only add new data to the bottom of the file but the right file overwrites whatsoever is inside that file with the new thing you give it give to it so if you do not want to overwrite your data all your file make sure to use the appen file all right so we want to write to the D bjon file Jon all right and then what do we want to write to it recall that it has to be a string so that means that at this point we need to convert the info the info array to what to a string so we stringify it passing the info into it and then after this just do a callback function inside it has an error all right and then now inside the function if we encounter an error so let's say there's an error we could just log to the console and say something like error over let's say error writing error writing to the database however if there are no problem we just log to the console telling them that hey data this has to be a string by data added successfully boom and that is it that is all you really need for this file so to put everything together we we will now call on the query DB file or sorry function recall that we have to call the function now also recall that we have to pass in this function that we just created into the query DB function so call on the add data and once you call it this way everything is set now what happens here is what happens here now is when we call on this file this function that is the query DB is run where this quy DB executes it executes with this external function which is the add data function and as it calls on this function everything here is executed down to this other part so the time has now arrived for us to test what we have done and see if it is working fine so node add data it enter and it says enter your name that's beautiful so put Samson or Sam is just fine let's put some number there and then here Samson is an adult well we have we have um an error so it's telling us that theb okay the file was created successfully um data arguments must be of typ string or of instance so where exactly is this error coming from where exactly I getting this aror from we got this Arrow somewhere around here so where exactly let's see if I can deug this here so okay f first WR file okay all right let's let's go back to here okay okay where are we getting this wrong data must be of type string or instance of buffer so for that we we converted this to a string here right yes that's what we did um uh oh oh okay okay okay so I I just realized that I I didn't pass in the info the info um uh array here so since I didn't pass it down it's telling me that um the data has to be of type string and well it's not of type string it couldn't happen so so let's let's do that it seen this as undefined and since it's undefined this couldn't work properly but now that I have all that cleared up let me run this again so okay let me let me go back to the top and start by deleting the file control k um and I hope you see that sometimes we we miss a thing or two and we have to debug look through our code and just be sure of what's going on oh okay my camera is off all right so node add data hit it like this and so we do not have a file yet then so let's um let's put in some all right then next thing that we put in some numbers and then yes correct the DB thejason file was created successfully and the data was added successfully that is actually what we are looking for I had to take a while to uh to debug my code and I I I just missed one thing and there was so much error now we have the db. Json file which we just deleted we have some data inside of it like the one we just created I could just create one more just so that you see a little of difference yes it's returning some data now because there is now data inside but let's create one with a yeah we add some numbers a okay let's let's say is a minor all right um you hit that and I think there's something we are missing when we go back here uh we are missing a key H so oh where this is supposed to be a lower case a i supp so let's clear this and try to add it again so if you notice it has not been coming in with the right Keys yeah it's coming with the right keys but not the complete Keys here so let's in jle hit enter numbers hit enter and this is an adult hit enter so what we'll do now is to try to retrieve data so retrieve data hit enter and good the last one now has has it right so uh you could just check in a few of these mistakes um let me just walk you through what um this code is all about all right so first things first we had to import a bunch of modules that are very necessary for for us to be able to achieve our goal so the first one is Inquirer the second one is file system third one is the uid and the last one is the query db. JS all right the next thing we did was to create an export this function and like I said this is actually optional you could just create an asynchronous function and push through next we collected data from the inquir sorry through the inquir using inquir do prompt we made the input into a data and added it into the info uh array that we already had then we checked if this file already exists that is the dbj file if the database is already there we just overwrite it with the new uh data that will have however if it it is not in existence then we use the appen file to create a new file and then call on the add details function in order for it to uh overwrite the db. Jason far please make sure you do not forget the info uh variable uh just as I did and I had to spend some time debugging now this is gener how it is for the Vel opers sometimes you spend hours days weeks or so debugging but it's all fine it's all how we learn and how we build better applications I hope you've been able to learn a whole lot about file system you generating user IDs uh using the terminal and all that the next thing we we'll be doing in the next video will be all about editing data so who pick this data that we have uh created in this video and edit them in the next video I will see you in that one too yep we are here now for the update data yes after adding data sometimes we want to update it we want to make some changes we feel like we made a mistake or so so that's what we want to handle here what we'll be needing to import here we'll be needing file system we won't be needing The UU ID anymore uh because the ID don't not change yeah other details may change then we'll be needing the query um DB file so just those and finally we will also be needing the DB file check this is totally necessary because um you know we need to check if the database is already there if it is not there we just terminate the process instead of wasting um resources stuff like that so I I will just um I'll just paste all that in so that okay let me just paste that in okay so as we continue we'll see where all this is leading us to so we begin as usual export default as sync function I believe all this now looks familiar update data all right it takes in info don't forget that it takes in info as argument and then we want to call the DB file check at the beginning here weing at the beginning so that nothing even happens since there is no file there is nothing to check so why stress yourself no reason next thing we create our try and Cat block and as usual we just past in some code all right that's working then what we need to do is to know which data we want to edit so how do we get to know that is where the unique ID comes in and that is why the unique ID do not change so let's ask the user to give us a unique ID we use the Inquirer again so we do const answers those answer should be fine answer equal to await Inquirer do prompt all right just one um one fi that's what we require now it will be of type input input like that name name is ID yeah name is ID and then message oh let's fix this okay message please [Music] enter data let's use record record ID that's it just format that a little bit now when we get this data what we want to do is to look through whatsoever we have in our database and see if we have the that data now if we have that data we'll keep it safe or hold it in a variable so we can use it uh in a bit so first thing is where do we intend to save it I mean save um the data that we get so we just set let's user let's call this variable user and then we now Loop through we use the info this point we use the for each Loop the for each Loop is also used by an array and some other kind of um data types too remember that we got this info from the query DB function so for each you open brackets and then inside of it you pick each data at a time so each of the data call each data element and then it takes in a call back function too so it's taking in two arguments that is one one is each of the data or an element representing each data and then there's a callback function where every thing happen so what do we want to check here we want to check if there is any match so if user sorry if elements do ID is equivalent to answer. ID then user becomes the element what we are saying here is if we meet any of the existing data that matches this ID that I was just pass in they will not save the data as User make sense beautiful now when this is done we will now come down we will now come down below this and then we'll try to update whatever that is already there in the user so for this we'll create a new function that would be will build out under this current function and we could call that update details update details do not forget you need two uh two arguments and that is the user then the info two of them so we now go down and build out this function this function will look very similar to our ad data uh function so you you don't have to spread it out so what we'll be doing now is a lot of repetition of what we've done before but they are very necessary as we are building out the rest part of our code so we just call on this function we'll call it update details recall it takes in the user and the info as arguments so what's the first thing we want to do the first thing we want to do is now to request for data sorry inputs for from the user and see where they want this inputs to be what they want to overwrite or what they want to update now something that we will do is to provide them with their initial value when we provide an initial value and they see the value and they feel like this value is valid they could just hit enter instead of rewriting or retyping that value now this is important when you have to write something that's more complicated that maybe just a name or phone number stuff like that so let's begin let's begin with our try and Cat block try cat block all right as usual let's paste this in here all right now first things we want to get is what the uh inputs all right so let's get those inputs the inputs we could use um okay now let's use let's use feedback feedback let's just diversify feedback feedback okay equal to uh this has to be a sync all right so that this is a way [Music] acquire do prompt okay open this and then this is yes an array of objects now what I am collecting here is the same thing I collected in the add data file so I could actually just paste this like this just copy this and paste it right in here but we want to do something extra we do not want to just collect this this detail like we said we want to also show them the default sorry we want to show them their initial um inputs as default so what we now do is we introduce one key for each of these uh inputs and that is the default so let's put it here and put default now where are we going to get this from we are getting it from the user that we just made or that we just saved and so here we could put user do name comma I hope this is making sense we we we came up here and we found the the user that our user wants to update now we came down here and we now passing in those details here so that if the user do not want to update it he can just hit enter and pass it by so user do phone down here we also have default it could be user do Ag and that's all format this and we have it nice and clean so if you look properly we now have the default added to each of them now when we try to update we will now see the the initial option or the initial value that was there this will all make sense when we are testing it in case it's not making sense right now all right now when we finish collecting details about this person what do we do we now want to update whatsoever or whosoever that we are working on so to update it we do user dot name now we are now updating it with the feedback we now say user do name is now your to feedback dot name user phone it's now called to feedback. phone user. H it's now equal to feedback. all right good so we now have an updated user all we now have to to do is to add this user to the info and everything is done we will now overwrite the database and everything is complete just watch it out that's what we are about to do next so what we're about to do next is to update the database and how are we updating it exactly what we've done before and what did we do before we just did await FS write file remember the difference between write file and appen file which file are we writing to db. Json after this what are we writing to it we are writing to it a stringified version of the info after this is call back function it takes in error as argument and here if there's error it tells you that there was an error error updating updating database if there's no error log to the console and say user this has to be a string too user updated successfully W and that is it our code is complete our code is complete so let's check is this working perfectly can we trust it all right we do node updates JS hit enter wo I think I made a mistake it should be update data.js and by the way we have not done one thing we need to do one more thing here which is actually call the function so we need to use Query DB and in the query DB we call the update data function hopefully everything should work fine this time around so hit enter it's working fine we have three data here right notice that this two doesn't have the adult um the adult key so let's try and see if if we can update that so enter the record ID hit enter now the name here we could change from Sam to Samson uh the phone now there is an issue here I need to check it's not showing the default uh value so where exactly did I get on wrong defaults defaults defaults okay okay okay let's see this okay just to be sure I think this was meant to be capital letter I think so all right let's save that I think it's supposed to be capital letters I think it's Cas sensitive um okay let's go again and paste that record hit enter boom it shows so uh this is case sensitive I think I missed it uh initially you need to check it out so that it doesn't mess up so we have some there so we could change it to Samson hit enter we have some numbers there you could change it to a longer number hit enter um something could be a minor so this is successful now just to be sure that everything worked fine let's retrieve data retrieve data data JS hits and where is Samson awesome now we're having two keys I think we we made some mistake somewhere around where we had the keys all right so this I think is supposed to be cap to letter we we need to it need to be this these things are K sensitive so that's why I have two phone numbers here to so this has to maintain the capital letters phone age yeah I mixed all that up so sorry about all that so let's try again to update data so update we will we'll pick this one that's not messed up yet I think everything should be fine this time around put it this way hit enter we have a barer we could change it to a be plenty hit it let's have a longer number now hit and okay let's leave it at yes let's clear this and then let's try retrieving our data again hit it and good we are no longer having multiple data like we had here and that is beautiful awesome so please um be sure to check for case Sensitivity I messed all of them up here when I didn't pay attention to that detail but let me walk you through what uh I have done here we began by importing modules as usual then creating a function but this time around we are introducing the DB file check which is supposed to help us to check if the database file exists now if it doesn't exist everything is terminated and the user has to you know check and maybe create data or check if there's something wrong now after that in the triy block we requested for the ID of the user after requesting for the ID of the US user we moved next to search for that user found the user and then called the update details function we passed in the user that we got and the info down to this function coming into this function we got back all the details that the user already had and put it in the default like this and so when we are asking the user for a particular detail this time around we are showing them the default too and so if they hit enter that default will continue to be there then we updated each key accordingly and then overwrote the file and that is it we have an updating application what is more we have one more thing and that is to delete data delete data there we'll be looking at how to remove any or all of this data that we have done I will see you in that one too all right it is the final video of this series and I hope you have been enjoying this series series as much as I have been enjoying it we have covered a whole lot we we started from the regular introduction to installing node to installing npm setting up the node project uh installing dependencies creating files uh checking if files exist reading from files adding to files updating files and now we are here to delete file yes that's what I want to do what we are going to do here is very similar to what you have learned already so it should be very easy to follow we'll be collecting the ID of um uh the ID of whatsoever data that we want to edit then we will look through the data there and remove every data that do not match to that one and then we'll keep those ones and use them to overwrite the file once we've done that the file is gone sorry the data is gone or deleted and then we have a new set of data that do not have a um sorry an entry that I we do not want boom that's all we'll be done in a minute so let's get started we need to import a few things and like you know we've used them before so we need the file system we need um the DB file check we need um we need the query DB and what more do we need I think that's all yes then the inquire inquire just the way we used it in um in the update file yeah all right let's start by creating an asynchronous function export default please as synchronous function so this one is remove data or it also takes in the info all right we'll start by checking if this file exists if the file exists we continue however if it does not exist we expect it to terminate at this point now let's do our try and catch block and we can just paste in this line here all right then first things first we need to collect the data that we help us to find what we are looking for and that is the ID so we could just copy this paste it in here so what we're doing here is to um ask the user to enter the record ID that's the ID of the data he or she wants to delete now after that we now do a little logic first things first we need somewhere that we can keep the data that do not match this ID and those will be the remant so as the name sounds we call it the remant so let's remant equal to say Remnant data equal to an empty array and now we Loop through the array that we have we could use the info do for each could just use for each and that's fine I think so for each elements so what we are checking is if elements do ID do not match answer do ID then add it to the remnant array so you do remnant. push what is it pushing into it is the element now what will happen is by the end of this iterations every element that doesn't match this ID would no longer be part of this Remnant and this Remnant is what we are going to be adding or using to overwrite the current data in the database now when this is done we now have a set of data that are new and do not have what we don't want and the final thing to do is just to go and overwrite the database again so let's go so we need await fs. WR file sorry right file db. Json recall it takes in three argument so the first one is the file the second one is data and we have to string the ify it so that's stringify so that we don't get an error Remnant data and then the last thing is a callback function it has No Name by the way just take in error as arguments and then if if there is an error all right if there is an error just rce this no this will be too small for you to see I'm trying to make so you see everything I'm doing clearly okay so if there's an error you could just log to the console and say uh error while updating database else we Lo to the the console and say record deleted successfully that is it the code is complete all right so let's do the final thing and that is to call the function inside of the sorry inside of the query DB function like that now we test what we have done sorry all right to test it we just do node remove data now let's remove this data that's messed up so we take the ID paste it hit enter and it tells us the record has been deleted successfully let's be sure that everything actually works well so let's do um retrieve data hit enter and boom we have just two well we could delete another one you know so let's delete this one so which one I removing we'll paste it hit enter delete successfully now let's check retrieve sorry that's not I want to do want to leave this retrieve yes hit enter we have one data so that shows everything is working but let me work you through what I have just done um we begin or began by importing all this the inquir the file system the query db. JS file the DB file file check. JS file to and then we first of all checked if the DB file exists now if it doesn't exist this code will be terminated however if it exists we will continue and that's why we continue all right next thing that we did was to ask the user to enter an ID for the data they want to delete now after they've given us that we look through each of the data found all the data that do not not match and kept them inside the remnant data now we now overwrote the db. Json file with the remnant data and so we now have a clean slate s of and that is how we come to the end of this whole application and if you look if you look at it you will see that this is a crow application and we did not need an external database we created our own database by oursel by manipulating file the way we wanted it now just to be sure that the DB file check Works let's delete this file that's the db. Json file and then try to run the code again okay so let's run it again uh I'm supposed to run remove data right node remove data hit and it tells us that file does not exist which is what it's supposed to be if you recall in our DB file check file see it all right so for me it's it's been really thrilling to make all these videos tutorials for um anyone who is watching um I really appreciate you being here uh and it shows that you you found something because this is the last video and there has been a whole lot I've been teaching and and is showes you want to be here uh I really appreciate that so what you do is please um to try something that I didn't do something I didn't do is trying to delete more than one item at a time or trying to update more than one item at a time try that and see how how strong or how well you've been able to learn nodejs and see how you could be better something I could also do is to add links to my um other no tutorials that a little more advanced than this and if you have these Basics then those ones wouldn't be much of an issue you will just scale through gradually and you get better NOS is really cool it helps you to build application fast and using the same language that use for your front end and that makes it really awesome so please do not forget to subscribe to my channel like this video and share it to everyone that you can share it thank you very much and I'll see you in my next tutorial
Info
Channel: Njoku Samson Ebere
Views: 182
Rating: undefined out of 5
Keywords: node, nodejs, javascript, tutorial, tutorials, programming, backend, beginner, beginners
Id: dGA3ojrt-fs
Channel Id: undefined
Length: 106min 50sec (6410 seconds)
Published: Thu Nov 16 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.