Become A Web Developer - Part 22: Node.js | Andrei Neagoie | Skillshare

Become A Web Developer - Part 22: Node.js

Andrei Neagoie, Senior Software Developer + Instructor

Play Speed
  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x
12 Lessons (1h 44m)
    • 1. Introduction to Node.js

      5:59
    • 2. Running script.js in Node

      3:05
    • 3. Modules in Node

      4:22
    • 4. Types of Modules

      5:10
    • 5. Building a Server

      8:25
    • 6. Introduction to Express.js

      8:59
    • 7. Express Middleware

      2:59
    • 8. Postman

      8:13
    • 9. RESTful APIs

      11:22
    • 10. Node File System Module

      20:11
    • 11. Exercise: Santa's Node Helper

      4:02
    • 12. Solution: Santas Node Helper

      20:51

About This Class

Node.js + Express.js

This is the tutorial you've been looking for to become a web developer in 2020. It doesn’t just cover a small portion of the industry. In this multipart video series we will covers everything you need to know to get hired: from absolute zero knowledge to being able to put things on your resume that will allow you to live the life you want. 

Sounds too good to be true? Give me 5 minutes of your time to explain to you why I built this course and what is different here than thousands of other courses all over the internet.

  1. There is no wasted time here. We won’t be using outdated technologies like PHP, Wordpress and JQuery. Although still useful, outdated technologies like the above are low paying and demands for them are decreasing. In this course, you will learn the specific technologies that are the most in demand in the industry right now. These include tools and technologies used by the biggest tech companies like Google, Facebook, Instagram, etc… It’s geared specifically for people that want to learn employable skills in 2018.

  2. After finishing this course, you will be able to apply for developer roles, or upgrade your job title as a developer and earn a higher salary. We won't be taking any shortcuts in this course. I am going to take your from absolute zero, where I teach you how the internet works, to mastery, where I show you how to build an image recognition app using a Machine Learning API (a subset of Artificial Intelligence).

  3. This course is taught by an instructor who has worked in silicon valley, and one of the top tech companies in Toronto. I have built large scale applications, and have managed a team of developers. I have worked directly with these technologies. I am not an online marketer or a salesman. I am a senior software developer who loves programming and believes that there needs to be a course out there that actually teaches valuable skills.

  4. I know your time is valuable. You want a course that outlines the best way to learn the topic in simple, well explained methods so that you fully understand topics instead of watching somebody on your screen and having no clue what is going on. I have created this course after consuming hundreds of books, tutorials, and online courses while I was learning. I have taken the best pieces, the best methods, that I have found, and condensed everything so that you can learn in the most efficient way possible. 50 hours of videos doesn't mean much if the instructor isn't engaging or focuses on outdated topics. 

  5. We have a thriving online chat community so you really feel like you are part of a classroom and not just watching videos by yourself. You will have a chance to communicate with fellow students, work on group projects together, and contribute to open source. Anytime you have a question you can ask in the chat and someone will surely be able to help you right away. 
  6. The course is designed to give you employable skills so you can get a job. Here is what one student recently wrote after taking the course and being hired right away: 
    "I’m a self taught dev, who has been out of work for ~6 months. I had some family things that came up that prevented me from seeking permanent employment, so for awhile I was Postmates/Uber delivery driver.
    After taking this course, I immediately got catapulted back to where I was before, but better equipped and with the knowledge to take on the next job. I had just finished the React section when I went to a recent interview, and it really helped me excel. As of today, I am officially re-employed back in the field, and it is all thanks to this course. I had a blast creating the final project, and FINALLY got around to learning SQL statements, and getting to use them in a project. I’m really ecstatic that Andrei went with teaching relational databases over something like MongoDB, which can also be fun, but is less practical for use on the job. So thanks Andrei , I really enjoyed the course and will be making sure to share it with others who find it helpful. I’m also looking forward to the new ES7/8 content that was recently added, and going through the DB stuff again when I go to build a personal project."

In this course, you will be taken through online videos and exercises where you will be able to do the following things by the end:

  • Build real complex applications and websites
  • Build an image recognition app together at the end of the course so you can add it to your portfolio
  • Go into a job interview confident that you understand the fundamental building blocks of web development and the developer space in 2018
  • Be able to go off on your own and grow your skills as a developer having built a solid foundation
  • Learn how front-end, servers, and databases communicate and how they all fit together in the eco system
  • Build your own startup landing page. 
  • Go off and remotely work by being a freelance developer and bid on projects.
  • Know EXACLTY what a day in the life of a developer is like and what the day to day technologies and tools will be that you are using. 

By the end of this course you will be comfortable using the below skills and you will be able to put them on your resume:

  • HTML5
  • CSS
  • Bootstrap 4
  • Javascript (ES6/ES7/ES8)
  • React + Redux
  • Git + Github
  • Node.js
  • Express.js
  • NPM
  • PostgresSQL
  • SQL

This course is the accumulation of all of my years working, learning, and teaching coding and all of the frustrations and incomplete information I have encountered along the way. There is so much information out there, so many opinions, and so many ways of doing things, that unless you have spent the last years working with these technologies in a company, you will never fully understand. So this course is the answer to that exact problem. I have gone through thousands of coding books and online tutorials and bootcamps. I have worked with these tools on real applications. Throughout the years I have taken notes on what has worked, and what hasn't and I've created this course to narrow down the best way to learn and the most relevant information. 

I will succeed if you succeed in this course. Therefore, I will be there every step of the way helping you understand concepts and answer any questions you have.

I am 100% confident that you won't find a course like this out there that is as well organized, and as useful, to build a strong foundation for you to start a new career. We're not going to be building simple todo applications and cat image sliders. We are going to learn actual practical skills that will put you into the workforce. Some unique sections that you won't find anywhere else are:

  • React.js + Redux: you will learn the library that companies like Netflix, Facebook and Instagram use to build fast, scalable applications. This is one of the highest in-demand skill in the industry.
  • A day in the life of a developer: What will your day to day look like and what tools will you use? I will take you through a sample day at a tech company.
  • How does the internet actually work. What is the history of these technologies: I will actually have you understand the underlying concepts of the internet, and how the technologies we have now, have come to be where they are.
  • How do you actually deploy a real life app so that it is secure, and won't get hacked: How does a real life app get out to the public?
  • What is Machine learning and how you can harness it's power: Whether you have heard about it or not, this is something that you will hear more and more in the coming years. Those who understand the high level concepts and can harness it will have an advantage. 
  • What is your developer environment on your computer look like: We will be setting up our computers with all the tools necessary of a developer so you can use the same setup when you go into the workforce.

Why do we teach the above? Because in this day and age, just knowing HTML CSS and Javascript is not good enough and you won't be able to grow in your role and command a higher salary. I am teaching you these things because these are the things you should know in 2018 so that you are miles ahead of the rest. 

Make this the year that you took a risk, you learned highly in demand skills, you had new experiences, and you received new opportunities. I hope you join me in this journey. 

This is the proudest work I have ever done in my life and I am confident that you won't find a course better than this. 

See you inside!

Taught by: 

Andrei is the instructor of the highest rated Web Development course on many platforms. His graduates have moved on to work for some of the biggest tech companies around the world like Apple. He has been working as a senior software developer in Silicon Valley and Toronto for many years, and is now taking all that he has learned, to teach programming skills and to help you discover the amazing career opportunities that being a developer allows in life. 

Having been a self taught programmer, he understands that there is an overwhelming number of online courses, tutorials and books that are overly verbose and inadequate at teaching proper skills. Most people feel paralyzed and don't know where to start when learning a complex subject matter, or even worse, most people don't have $20,000 to spend on a coding bootcamp. Programming skills should be affordable and open to all. An education material should teach real life skills that are current and they should not waste a student's valuable time.  Having learned important lessons from working for Fortune 500 companies, tech startups, to even founding his own business, he is now dedicating 100% of his time to teaching others valuable software development skills in order to take control of their life and work in an exciting industry with infinite possibilities. 

Andrei promises you that there are no other courses out there as comprehensive and as well explained. He believes that in order to learn anything of value, you need to start with the foundation and develop the roots of the tree. Only from there will you be able to learn concepts and specific skills(leaves) that connect to the foundation. Learning becomes exponential when structured in this way. 

Taking his experience in educational psychology and coding, Andrei's courses will take you on an understanding of complex subjects that you never thought would be possible.  

See you inside the course! 

Transcripts

1. Introduction to Node.js: Welcome back. It's time to learn Node Js now, No Gs. We've kind of used it in previous videos, but we haven't really explained it. So throughout this section we're gonna learn what it is and finally use it to build a server. Now, I may have mentioned this before, but node is javascript that runs on your machine. You see up until note was created, you could Onley run JavaScript in the browser because the browsers were the only ones that had a JavaScript engine like V eight and no Js was created with the V eight engine in order to be able to run JavaScript anywhere, including your computer, including on robots and anywhere as long as you had no Js. And as a matter of fact, we've been using node this entire time in our terminal. When we ran commands that NPM gave us, like, create react up Well, that was using note. We were running javascript outside off the browser. And no, gs is probably the most popular for building servers. It's really, really fast and more more companies are using it now as a back and server because of the way that it's built. No Js is probably the server of choice for any Web abs or mobile apps out there that want to create an A P I or server. And it's also really, really good at building chat applications and real time communication. Anyway, as we've mentioned before, you probably should have this on your computer by now. But if not, you can download no Js. I like using the LTs version, but as long as the version that you're using is higher than a 0.9 point three, this demonstration will work for you. Note is really, really good and making sure that everything is compatible again. If you're using a Windows operating system, then note provides that for you in the Donald section as well. And again to check. Note. It's very easy. We just do no to dash fee to see that we have it. And if you do have it, you'll have the version number printed for you on the console. One last thing before I show you some note commands. Like I said before note, can be run anywhere, and one of my favorite things to do with note either than built servers is to actually create robots using JavaScript. This Johnny five is a JavaScript library that you can use with note. And if you have something like a raspberry pi, it helps you build functions using JavaScript that robots can perform so highly, highly recommended after this course. If you want to explore more, Johnny five is one of my favorite things. And it's surprising how easy it is to build a robot that does whatever you wanted to do, just using JavaScript. But anyway, let's go back to note in your terminal. If you actually type in node and press enter, you'll see that the prompt changes now and I can run note in the terminal. If I do console dot log Hi, I get high. If I do four plus five, I get nine. And if I do bullion three, I spelled that wrong bullion. Three. I get true. As you can see, we're just running javascript, but there is a bit of a difference here. If I type in window, I get a reference here. Window is not defined. And let me clear this a little bit. This is because when we run note we don't have the window object. The window object was provided to us by the browser. And, as you know, node, well, there's no browser that's running it. Instead. Note comes with something called Global, and you can see that this global has just like the window object. Had a bunch of things that we can use, but it won't have browser specific things. For example, we won't be able to have global dot fetch. It's undefined because, well, it doesn't exist. That was provided to us by the browser. We also don't have the document object. If you remember, I do document again. I get a reference there because, well, there's no document, so that's something to keep in mind. Node comes with its own properties and methods that we use, but other than browser specific things, we can do anything we want with note. One of the global objects that we have is something called process. If I press enter again, I have a ton of stuff and in node process means this process. What I'm running right now in the terminal is the process. What the computer is doing all right, and let's just clear this now. If I do process dot exit, I exit this process. And now I'm back to my terminal. Now that we have knowed in our power, we're gonna start writing some scripts and show you how we can start writing actual JavaScript Not in the terminal, but in sublime text. I'll see you in the next video, but by 2. Running script.js in Node: Welcome back. Let's expand on our node knowledge from previous video and actually create a script file that we can run. Let's just do the touch command here again to create a file, and we'll just call it script dot Js. You'll see if we're here on the left hand side that ah half script Js in my note folder now within this folder, I can now do anything in Java script. I can say const A. Equals five and that's not the folder that I want. We want to open this and will say Constant A equals four const. B equals five. And then we can just console old dialogue a plus B. If I save this in order to run the script, all I do is note and then the script me script dot Js and because we're in the directory will know what script Js is and I'll give us night. How cool is that? Now you also see that it exited. It didn't stay in the program, and that is because at the end of the file, once it reads everything and executes it. So the last thing it executes is consul down log. It runs process dot exit and exits out of the five. Let me show you something. If I did something called the set time out which we actually have a note. If I do note global dot set time out, I get a function. Okay, So if I do said time out, I can run a function again using our higher functions. And within here I can do console, log and set time out is cool because it allows you to say, Hey, when do you want this to be executed? And that's the second parameter and I'll say three seconds. So if I save and I do note script dot Js 123 and there you go nine and then process exit notice. Smart enough to run through this Once this is done and the process and comes back to the terminal very cool and again within note, we can actually use things that might be useful for us based on what global objects we have . For example, one of the most popular ones are underscore underscored her name. If I save this and run note script Js again my directory note and also you, why that's useful when we start building a server. But as you can see, we have the power of the browser and running the scripts that we want right here in our terminal. I'll see you in the next video, but wait. 3. Modules in Node: now going back to my example here. Let's add a new file and we'll call this script to dodge a s. Now the script you that Js can have a constant called large number And let's just say that's 356. And if we want to export this and say Export default a large number and now within script Js I do import a large number from script two dot Js. Let's make this a little bit smaller and now I change this to a large number and letters do a plus B. If I run node script Js I get an error unexpected token import and that is because node has yet to implement the new E a six feature of imports statements and there are ways around it and you can add packages in order to allow you to do this. But I'm gonna show you the common Js way because most servers that you'll encounter will have the common jazz way and over the years, this and this will become more prevalent. But you already know how to do this from the front end section. So nothing is different here in order for you to get familiarized with common Js We're gonna use the require for So how can we do this using the way it works in note 8.9 which is the version that we have What will will have to do a const A large number equals require again This might be familiar and then within here we have to give it the file bath with require We now have a large number and we also want to export it now And the way exports work with common Js is you do module dot export And that is because Let me just clear this and show you If I do note and I do module you see, that module is a global object that we have access to and using module daughter exports. I can say what objects I want to export in this file. In our case, it will be a large number if I save this And now run our note script. We got to exit the process first. To be clear, if I Ron note script Js I get object Object Five, Huh? Why is that? Well, because now we've exported this object and the way we want toe access it here. We're exporting a global object, which we can name whatever. In our case, we can say script to and in order to get the property off script do well, we'll say script to dot large number. And now if I run this, I get 361 and this could be named. Anything is just a variable that you're declaring, so we can just call it see, see large number, and it still works. It's a bit of a different style than we used to on the front end, and that's only because we haven't implemented the or no, it hasn't implemented the import and export with this version of it, but it will come eventually. Just don't get scared if you see it this way. Once you get used to the syntax, it's pretty much the same. All right, I'll see in the next one. But by 4. Types of Modules: Welcome back in this video, I want to talk to about three kinds of modules that you can have in note. We've seen that we have this type which we already know about, which is a module that you create yourself like script to and has its module exports, and you give it the path, do the file so you can find it. There's also something called built in modules and built in modules. Our modules that come already preinstalled with note. For example, one of the more popular ones is the FS module. And this module. If I console log is a module with a whole bunch of things once again, but it allows you to read the file system. That is, if you had a text file and you wanted to re through the text file and extract out how many times the word hello was said, Well, you can write that by simply using the file system module and using something like Read, file or read File Sync, which will up put you something like read file. It will output the contents of the file, and then you can do whatever you want with it. Another popular one is the http module, which, as you can guess, is the module that will use later on to build a server. And you can read up on all these modules. But those two are probably the most popular in our case, as Web developers were really concerned with the http one these modules are without the path there just simply exactly like that. And then finally, the third type of module again the one that we know is something from NPM A package on one of my favorite packages to use with note is something called Node Mont and no Moniz really , really nice because well, if I clear this and install NPM install and I'll have to do npm in it first, actually, to make sure that I have a package dot Jason file And if I passed the dash, why, I will just say yes to all the prompts that I get beforehand. There you go. My package not Jason. And now within this package dot Jason, I'm going to say npm install no daemon Dash, dash save Dev, If I go to Patrick about Jason, I see that now I have no Damonte in Dev dependencies and we haven't seen this before. Up until now, we've done either dash, dash safe or nothing at all and automatically put it in dependencies. Deaf dependencies are dependencies that we only use when we're developing. When we actually released this app or this server, it won't be included because no Moniz, just for again for our enjoyment while we're developing. Now, let me show you what no man does. No daemon now can be used because it's in known module. And if you go Tobin, you see note bond here. Well, because it's in the package known modules dot been. I can use the command such as start and say node mon and notice smart enough to know that if I run no Damonte, it's gonna look in the dot bin folder and find it there if it finds it there, which it does go around the command. So let's see what happens if I clear this and do and PM start. I got a bit of an error because, well, we have some weird falls in here, so let's just go back to our original example. Let's save run NPM start and we have a clean exit. But you see that something is still running. If I change this now to six and I save it will watch those changes for me. It keeps listening to changes, and it will up put everything again if I change this so I don't have to keep running the node script dot Js Command Very cool. So we'll be using notam on a lot. And it's one of my favorite things to use again so that I don't have to go back and forth, back and forth. And if you make any mistakes, well, it will let you know right off the bat. All right. Perfect. That's it for now. I'll see in the next one, but by 5. Building a Server: Welcome back. I think it's time to create our own server now. So let's create a new file called server dot Js. And in order for no one Montu, listen to server dodgy s largest type in node one and then server dog Js. Now, if I say this, Nordmann will listen to this as long as I say NPM start as I've mentioned before, Knowed comes with its own HD TV module and that's what we're gonna use to create our server . And it's very, very simple to use. We simply grab the HDP module and then create a server by defining it saying, http, create server and this creates server will create an air function and within here for now, delicious to consul dialogue. All right, here, you. Thanks for their request. And then finally, we have to do server dot listen and give it the poor number that we want to listen for. So let's do 3000 for now, But again, you can do anything you can do 3000 and one if you want, but 3000 is nice. Let's do node server dot Js and it looks like it's just hanging there. But let's go to pour 3000 on our local host. That is our machine and see what happens if I open up a new tab and go to local host 3000. Nothing's happening. If I open up the console, nothing's there. But if I go back, I see I hear you. Thanks for their request. And that is because remember, server dot Js is running in note. It's running here in the terminal, but it's listening to connections. So when I hit, refresh here or I press enter and try to connect, it will be listening and it will run console doubt. Look, and you can see that the second I hear you. Thanks for the request this year. If I refresh two more times well again, I get two more. But right now the browser is just hanging there because we're not doing anything. We're not responding with anything you can see at the bottom, it says, waiting for local host. We're just consul logging on our end, but we're not giving any response. Let's do that. I'm going to remove the console log and use the parameters that creates server gets us. So any time we try to connect. We have a request, then a response parameter that we can use. And let's make this a little bit smaller just so we can see. And within here we can do something like response dot said header content type. We're letting you know what kind of content we're gonna send and it's gonna be text html and this just a standard way of declaring content type and we'll say response and with and H one tag that says Liu. If I see this and we run well again, we have to restart our server. So let's get known Mon involved in here so that it listens to file changes. I'll go to Package shot Jason. I'll save this and now Ron NPM start. See that everything is running. Let's go back to our server Js file. If I go back and refresh, I get hello If I go to the network tab, I see that local host I get a 200 response. If I click on this, I see that the response waas H one Hello. If I goto headers, I see that it was a 200 status code and the content type was text a CMA very cool. I can also listen to requests. So for example, in here, I could have said console dialogue requests headers I could have also said could have also said method. And finally, something like you're all requests gives us a lot information about the request that we received. And just so we're clear on what each one of these are, I can say headers method and you are out. If I say this and rerun, I see that I get headers are local host 3000. We see that user agent was Mozilla Macintosh. So that's what we used. We use an apple to make that request, all right? And the method was a good method. And Earl Waas just the backslash just comment out the headers for now and show you how the exchange if I now enter local host profile 123 I get method get and you're Al was profiled 123 So we get information about the request that the front end made, which is very cool now, without response, we responded with texts, html. But you remember Jason, right? We talked about how useful Jason is when doing Ajax requests. Can we do that here. Of course. If I go and change content, Type two application, Jason, and you'll just have to get used to this. But this is the way you say that the content type is Jason. Now we can send a JavaScript object such as user and we'll say name John Hobby skating. Now, this user, I can pass here. But remember, in order to transfer between the wires and we need to use Jason dot stringing fine. And make sure you check out the Jason video, if that is confusing to you. But again, we're changing this object into a Jason String so that we can send it over the wires if I save and let's go back and refresh I get Look at that. A Jason response again named John Hobby Skating. If I click on the network tab here, I see that the content type is application, Jason, and the response is in Jason format. So on the front end will run Jason dot parse and then this in order to convert it to a JavaScript object. Very cool. We just created our very first server. But this http is pretty bare bones as you can imagine building servers is something that everybody does that has a website. And there are many tools that we can use now that are more elegant than running http. And the most popular and the best one to use with no Js is something called Express, which we're gonna talk about in the next video. I'll see you on that one the way. 6. Introduction to Express.js: welcome back. As I mentioned before, developers are really, really good and making sure they don't keep doing the same thing over and over. And if there's anything that is done over and over, they build a tool for it so that it becomes simpler. What building servers was one of that? It's something that everybody uses. So people use libraries just like we used react on the front end on top of JavaScript to make our lives easier and build faster, more robust servers. And there are many libraries that people use with note to create a server. But the most popular hands down the best one right now is express, and I have here the state of JavaScript 2017 survey. It's a famous survey that gets done every year at the end of the year. That asked developers what their favorite tools are, what front end tools they use, and I highly recommend that you check it out. But you can see here for the back end the library that this most popular is express, and this purple bar means I've used it before and would use it again. There's other ones like koa meteor happy, but the usage is very, very small. Expresses just a tried and tested. There's plenty of tools and information online for it. So if you ever get stuck, you're able to find an answer to your issue right away. So expresses the way to go in 2018. So let's learn some express and show you how much easier it becomes to create our own server. So we're gonna delete the server that we built previously in the last video and it's still express. Let's do NPM install and again through MPM we have the express package and now we have expressed available to us. So let's grab it that way you create a express server is very simple. You simply do express, require express. We have to do a const up and then to created that app to run express, we simply do express and then finally abduct. Listen 3000 and that's it. We have express running. Let me do NPM start and we see that our notes server is running and if I go back to local host 3000 I half cannot get. And that is because, well, again, we're not doing anything. But in just three lines. We have a server and I want to show you that Express has great a great guy to getting started and a ton of information of how to use it and documentation free that you can check out on your own. But for now, let's build our own well, express is really, really good at doing around. If you remember in our local host, we got cannot get to do a get request with express. We simply do app dot get And the first parameter is the path we'll just do the route path, and the second parameter receives a request in a response and an express instead of writing everything out. The common way of doing it is doing rack and rest. And in here we can say response dot sent and we'll just send a hello, just like we did in our previous video where we used the http module that comes with note. So let's check that. Let's see if that works. I'm gonna save refresh, and I get hello. If I open up the consul here in the network tab and I refresh again, I see that the response is hello. We see content type texts say she mill that was converted automatically for us. I can also instead off, send just an HTML. So instead of doing something like each one and each one, which gives us an H one Hello, I can also now send Jason caused user again. And this time the user name will be Sally and her hobby will be soccer and me too at unequal here and then passing user If I say that and go back and refresh Look at that. It automatically does the Jason string if I for me and returns a Jason content type an application Jason Condon type with the response that is Jason. Very cool. So you can see the part of express. Even just from this simple example, it takes away a lot of the repetition and makes our life a whole lot easier. Now we've only done get here. But you can also do post to request. So, for example, if I did post profile well, now if I refresh, I get an error because because now I've made the request method which was get from the Bowser. But here I only except a post request from profile. If I do profile here I get cannot get profile because even though we are going to the proper, you are all now we're doing a get request. Any time we refresh your browser, it's a get request. And in order to do that, we need to actually send some data over, and I'll show you how to do that in the next couple of videos. But just to show you how express works, I can keep adding these routes. Let's do get profile that returns getting profile. And if I do a another, get this time to the root, your l and this one, I'll just say getting fruit. If I say this now and refresh profile, I'll get a 200. Okay? With the response off getting profile and if I do know profile and just the route you Earl , I get route. And the way express works is it checks each one line by line. So, for example, it will check. Hey, did the get request have their rule? Euro did the get request. Have profile. Did the post request have profile? And if it matches any of these well, it will run. Whatever the function inside of it is if I do a u r l that doesn't exist. I get a 44 not fund because, well, we did a get request to this girl that doesn't exist. So using this that we can use the get method, the post method, the put method and the delete method that we're gonna actually demonstrate in the next couple of videos. But as you can see, it's a simple matter off saying, If you go to this route, do this. If you go to this one, do this and everything is just logical and trickles all the way down. All right, I'll see in the next video, the by. 7. Express Middleware: Welcome back in this video. I want to talk about an important concept and express. And that is middleware. Let me show you how it works. If I run the server here, I just have a simple server. That sense Test Express has a concept of middleware. And if I do app dot use, this is a generic express middleware that I can enter in here. And what middleware does is as the name suggests, as the request is coming in, it's gonna pass through this use function and then trickle down to whatever we get post put delete. And this middleware is gonna do something to the request that we just had in order to perhaps make it easier to work with down here, let's demonstrate that example app that used receives a request response and then something called next. And within this function, we will just say console dot log H one. Hello. If we save and go back here and run local host, it's a hanging here. Even if I open up the console, nothing's happening. If I go back, I see that hello gets triggered because I'm consul locking it. But it never reaches here. Well, That is because in order for the middle, where to keep passing data through in needs to call next the third parameter. So now by calling next if I refresh, I receive test test. So the middleware the way it works, is we use app dot use. It gets the request off the the website. The request comes through. We can do whatever we want with it. In our case, we're not really touching it. We're just consul logging Hilo, and then we hit next and then express keeps running through these. And although you might be thinking, why is this useful? There are many, many cases that I'll show you later on. While middleware is important and middle wears are great scripts that people have pure in that you can add to your server, but you'll see that mawr in the next video. I just wanted to show you the basic concept off middle, where something that receives ahead of time before yes to the routes, the request modifies it and then passes the next function to keep it going. I'll see in the next one goodbye 8. Postman: Welcome back. Let's try and get this post request to work that we couldn't get in the previous video. Now, in order for us to test something more than just get well, we can use the terminal. But there's a really nice tool that allows us to make these requests to a server and see what we get back. And it's called Postman. If you go to www dot get postman dot com, it is one of the best tools. If you're ever working with the server, it's free, and you can download it for your operating system. Just simply click on whichever one you want. Sign up, and once it's loaded, then you can open it up and you'll have something like this. And don't worry. It's very, very simple to use. We simply have here the requests that we want to get. You'll see a few that you've never seen before, and don't worry about them. These are very, very rarely used. We see the ones that we care about. Delete poot Post. Get right there and you simply enter the URL that you wanna have this running on. So, in our example, let's do NPM start again And while the server is running, let's just go to profile, get profile. And then in here we want to say local post 3000 that support that we gave it and we'll say profile. So we want to do a get request over here. If I click send, I get getting profile. It gives me the headers and the body, which is great. But now, because we have this stole, we can also do a post request. So let's say that we're no longer sending the user. We want to send a response, and from this response that we want to return whatever user that we submit to profile. So let's start off here first. We're gonna change this to a post and with a post. Remember that we can, actually, thanks to the body and you see over here that there's a couple of options form data the ex www form on your l encoded we have raw and then binary. Now, don't let this scare you. These two are forms through HTML. If you usually do an HTML form tag and do a get or a post request, you can just click on this and you can see here a key value, so I can say name equals Andre. And now when I send this, I get Sally and soccer well because, Well, I haven't saved this yet. Let's go back to what we had before and send that again. We see that the Post requests is working, and if I want to access this information, I simply do quest dot body. But let's see if this works. If I click, send who I get undefined, and that is because express Onley gives you a little bit. You still need a few packages If you want this to work, if you ever want to access request dot body. Well, you need to use a middleware, and the middleware that we want is called Body Parcel, and you'll use it in most expressed servers, so you'll just get used to it. It's NPM install body part, sir, And now this body part, sir. What it's going to do is it's going to grab whatever information we receive and parse it just like Jason or forms into something that we can use in order to actually use it. Well, we know how middleware works. We simply at the top say app dot Use and body parts, sir will come with a body parts, sir, That will just require with the package that we just insult inapt I years we simply do body parsa dot You are old and coated, which is how we're able to get this and we just have to pass it a parameter extended to false Let's try that again. I'm gonna safe going to npm start if we go back and send again We see that There you go. It's working. Name is Andrei because we've sent our key value with formed at so if you're building a server for a form that gets submitted, you'll use this. But as you know, there's also Jason that we can use. And the way we use Jason is we click on raw and in here we can send whichever things we want. In our case, it's going to be Jason. And with Jason, we can now say what we want to send. And if we ever do any wrong, syntax will tell us that this is wrong, Jason. But let's just say for the profile I want to add a new user, and this user will be called Remember, double quotes. Here we'll have user, and this user will be called Jenny and Jenny will have a hobby of tennis. Everything looks fine. That's Jason. If I now send this, I get an empty object again because we've only told it to parse. U R l and Coated Body Part Sir Niecy also know about Jason again. In order to do that, we say up down use body bar, sir dot Jason If we say that and send again look at that, we have user Jenny Hobby tennis. So now we can add that user by maybe adding it to our database and then sending a response . Success. Let's try that again. We get a response success that we've posted Jenny tennis In this way. We can also do put, which is very similar. We just send the data, but put is used for updating. If we want toe update perhaps Jenny to have a different hobby and delete to delete maybe the user something that will get into the next video. But as you can see, postman is great. It's a great way to test how your server before you connect it to your front end something that will definitely do in this course in our final project. Very cool. I'll see in the next one. Bye bye. 9. RESTful APIs: Welcome back in this video, we're gonna talk about rest ful AP eyes. Now what is that? Arrest? FBI defines a set of functions which developer skin perform requests and receive responses via http protocol such as Get post put delete something we've talked about. Remember how I said a Web browser sends a request and just hopes that the server returns what the browser asked for? Google servers can send us whatever it once it doesn't have to follow the rules that perhaps the Web browser sets with rest ful a p. I were able to create an A p I. That is rest ful something that follows the rules that everybody can agree on so that we have compatibility between different systems. So arrest fel a p I is an architectural style, and it's an approach to communications, then agreed upon set of rules. So everyone plays nicely. Arrest full AP I uses get to receive a resource put to change the state or update a resource, a post that creates a resource in a delete to remove it. And that's something that we've already talked about and the rest ful a p I is a way to define our server so that it specifies what it can provide and how to use it. And, in other words, the U R L parameters should make sense. For example, if we're doing slash profile, well, we expect that if it's a get request, we're gonna get a profile. If it's a post request, we're gonna add a profile. If it's a put, perhaps we're updating the profile and this u R L makes sense, and you can think of this as the noun of what we want her receive. The http request is thieve herb and everything After the slash is the now now, finally rest AP eyes are something called stateless, meaning that calls can be made independently of one another, and each call contains all the data necessary to complete itself successfully. A server doesn't need to keep memorizing things. Each request that comes in has enough information that the server can respond with, regardless of who that person is. So in this example, let's build a small little app that has a rest ful a B I. Let's make this a lot smaller there, you know we have our previous example will start the server and talk about some of the things that we can do. You hear? Well, when we look at a get request this get request, let's actually remove. This is well, just so it's not too Messi, This get request will have a request object that we receive Now this request object can have a few things we can have requests That query we could have request dot body, which we saw in the previous video. We also have request dot header again something that we've seen before and also request dot parents And this is probably the most used properties off requests. So let's go through it one by one request Our query is what we get when we do a get query. For example, within here. If I do a consul dot Log Request Quay Well, I can go to local host and in here something that we've already talked about. I can add a question mark to say that this is a query string and say name equals Andre and Cage equals 31. My breasts enter Go back and I see here that I have name is Andre. Age is 31 because I have access to the choir ST We also have request body, which again we've talked about using something like your l encoded or Jason body parts. There's we can add that middleware too receive whatever the request sense in the body. We also have request dot headers. So if i console dot log request dot header Well, this time using postman, I can say in the header and it has a nice header Stab. We see that we have content type application Jason which automatically does it because the last request was a Jason request. But I can put in anything here. I can say name is Andre or this time just to change it will say, Sally, if I send this Oh, and this is a dilly method, Let's make sure it's a get method. If I send this I see that now Request out header have all these headers, but also name Sally Very cool. And then finally we also have something called request stocked cramps. And if I console log request operandi, this is a syntax where you use the parameters of the URL. If I do the semi colons and then let's say I d I saved this and now we have access to whatever the parameter is of the URL. So let's just say 1234 and I'll remove the header for now. If I sent I now have I d want 234 right? Awesome. And you can have as many parameters as you want and you could ness them. But we have access to our request information, which is fantastic. Now, when we send a response, we also wanna have a bit of ah on option as to what we wanna send. Well, with a response, we can say that with sending We also want to respond with a status the say status off 404 and we can say sent, not found. If I refresh and send now, I get not found. I have not found with a status off for four again. If I go back to my browser and refresh, I have in my network tab a four or four status All right. Perfect. And again you customize so that we have a rest ful FBI, the get post put and elite to follow the rules that the Web browsers expect now. One last thing Up until now, we're just sending data back and forth. But what if we wanted to serve something called Static Assets? That is indexation Mel CSS file. JAVASCRIPT file That's more realistic, right? Usually we want an index file and having our app run well, that's very easy to do. We can create within this project. Let's just to a new folder, Cold public. And this name might be familiar to you because we need to create react up Public was there and it held Oh, are static files. So in here alleges to a new file index dot html. Now, within this public file, we'll just do a quick HTML document that says Hi. And within here I'll say it's working in order to get express to send static files. We can just remove this for now just to keep things clean and do another middleware app dot use. And this comes with express. Already we do express dot static and within here we give it the file path. In our case, we know that we want to get the dirt name which we've seen in previous video, which is the directory of where we are. In our case. It snowed and we want to go to the public folder. So we do public this is gonna print out node, then public. So now if I save this and go back to our give request, I get it's working. Will you make that bigger sequence, e? And if we open up our council and our network tab, I refresh, I get who leads to ah, hard refresh. I get 200 I get text html and the response is my html five. And if I had CSS blink here, it will load the CSS in my public folder. If I had a javascript file, then it will load it because within the body, we can add a script AC and this is a server that we just built that serves simple static assets. And as soon as we wanna have something like an A p I where we interact with that, we do get post put to delete. That's when we start using our methods that we learned previously. Vehicle. Now that we have this basic foundation, we're gonna build our server for our app. The app that we build in our final project are in his recognition app. Well, we're gonna build the back and for that now I'll see in the next one the way 10. Node File System Module: Hello, everybody. Welcome back. And in this video I want to show you something that got me really, really, really excited when I first started learning note. And hopefully yet Justus, excited as I am as we go through this video and then do a little bit of a challenge, it's gonna blow your mind ELISA did for me when I first started learning to code. Now, in the previous video, we talked about something called the FS module that comes with note. And this is something that is built into note. And the way we get it is will we just do constant? Well, actually, we need a fall first. Soulless. Do a touch script dot Js will create a new script. Perfect. All right, we can close that cause we don't need this. And in the script dot Js that we have in this folder. Awesome node, we can have const fs equals require half s So fs here stands for false system And if you have no downloaded, you have access to this. But just doing this now why is this so exciting and so useful? Well, because fs file system allows you to access our false system, which can doesn't sound that exciting. But let me demonstrate what happens and why this is useful. So bear with me here, I'm gonna do a bit of coating, and then I'm gonna explain exactly what is happening. So we're gonna use the fs read file. It's pretty self explanatory. We have a blank parameter, and then we have here before air data, and this is a narrow function. So the second parameter is a function, and this function has either air or data. So for the error, I'm going to say if there is an error, we'll just throw here. Or we could just say console dot log hair to really shove it into their face. Hurt. Um, now, if there wasn't an error, we'll just say we'll just say console dot log and we'll just log out whatever dad eyes. All right, let me have the semi colons and save that. So what I just do here? I just imported the FS module that comes with node and the FS module has a method read file that Well, it looks like it reads some sort of a file. The first parameter is actual file that we want to do so The path to the file, which we don't have yet. So let's create one. I'm going to say a new file and we'll call it hello dot taxed and with hello dot text will do our classic Lou there and exclude exciting stuff. So, exclamation marks. We saved that. And now we can say that we want to read the file. Hello, taxed from the current directory hello dot text. Now this read fall method is gonna find the file with the path. Okay, so here's here it is. It's going to read it. And then if there's an error that's going to spit out an error, if there's some sort of data and everything successful, it's going to speed a spit out data with the way we can run this fallen note, well, we'll first have to save it. I will say node script Js enter and I got Buffer. What is that? And that is because we have to do a little bit off and coding. And what that means is, if I could do this to string, let's try this and show you what I mean and I get hello there. So the read file, reads the file, as the name suggests, and it's going to spit out whatever it's reading data now, Why do we have to put in the two strange here? Just so you know, to string does something by default. If you don't add anything, it's going to use the encoding called utf eight and utf eight is a type of a coating. Let's just run this to make sure that this is still the same. Yep, so UTF eight is a type of encoding that we have that's pretty standard with HTML five and pretty much everybody uses it on the Web. It's a way for us to have characters, whether their land characters, no a B C's or we have Korean Japanese Chinese characters. They're all represented by a number. And utf eight is a way of encoding these numbers to make sure that we can read them. It's actually quite a complex subject, so I recommend the Wikipedia page that talks about utf eight for now. Just no, that utf eight is a type of encoding that is pretty much standard across the Web. You might have also seen asking and ask. He was before utf eight existed. Ask. He was mainly for Latin based languages, so the A, B, C's and utf expanded that to include many more from many more languages from different parts of the world. All right, a little bit of, ah, tension that we didn't need to go on. But as you can see over here, we have hello there and were able to read the file. All right, very cool. Let me just add one other method to your repertoire. Let's also do fs dot read file sink and refile sink works a little bit different than the previous one, and sink stands for synchronous. So let's see what happens. I'm going to put in hello dot text once again, and this time I'm just going to leave it like that. And let's just say that this is going to equal the file and we'll just console doubt log the file. All right, let me say that and run this. All right? We know once again that we got this because we need to do do you strength. So let's do that. I'm going to to lips to string, going to save and run this again. Alright, I get hello there but just to distinguish them. Let's just say that this is number one and this is number two. I say this, run this again and whoa would just happened. We have one coming after the two. Now, if you've washed the a synchronous synchronous video in this course, then you might understand what's happening here. If not, I'm gonna do a quick synopsis. But I do recommend you check out that video now read file is a synchronous, and that's why it has something called the callback function. It is saying, Hey, I'm going to read this file and when I'm done with it, you just keep going on with your business and keep reading line three. Line four, Line five from line six all the way to 11. When I'm done, I'll let you know, and I'll either give you an error or some data read. File Sync, which is synchronous says, I'm going to read this file. Don't do anything. Just wait here. When I'm done, I'm going to assign it to file and then you can keep going. So as you can see here, what happens is we read the file and because this is in a synchronous it's going, Teoh, run this and come to Line 10 and Ron, the FS read faucet and the read file saying, because it's saying, Hey, wait until I'm done. This is going to print out Hello there and then the a synchronous code is going to say, Hey, I finished reading the fall. Here's the data and it prints out down over here again. I really, really recommend you check out the asynchronous synchronous video. But for now, hopefully that makes sense. Now, looking at this, which one should you use? Well, for a simple case like this, we can use whichever we want. But you may see a problem with the 2nd 1 especially for building something like a server. If we have a massive file that has something more than hello there. Well, if we're doing read file Sync, what happens is we're gonna halt or pause the execution of our file, and it's going to read the entire text and the program. Just gonna be waiting for that to finish versus the read file, which says, Hey, you can keep going ahead. I'll let you know when I'm done with this. So when you're building a server and, let's say, an express server with routes. Well, in that case, we want to use read file if we're reading any sort of a file or text file, whatever it is, because that way we're not blocking the execution and the program can keep doing things. All right, so one last time just to clarify things, I'm going to label the says a sink and sink. So once again, if we run this, we have a sink and a sink. Hello there. Very cool. Were able to read a file and both instances, which was kind of cool. Let me show you a few more of these and then tell you exactly why this is so exciting and how we can use it to do some really exciting things. So let's say the hello there. Tax is kind of boring, and we wanna add to it. Well, we can do something like this fs upend file. We give it the file we want to upend. So in this case, it's Hello, doc text and by the way, if this doesn't exist, will actually just create the file for us. And the second parameter will say what we want to add. So let's say we also wanted to add maybe a space. And that says this is so cool. Now they're exclamation mark and finally, third parameter takes it on air. And this error will just say that if there is an error, let me make the smaller so you can see we'll just say if there is an air. Well, just console dialogue. You cannot type here. All right. Perfect. So let's run this and see what happens. I'm going to on the script and I get Hello there. Hello there Because these ran first. But if I go to Hello? Text. Look at that. We just wrote to a five and now we have This is so cool. So if I run this again and let me clear this just so we have more space look that I get Hello there. This is so cool. Hello there. This is so cool. If we go back to the hello dot text file Oh, boy, we've added even more. This is so cool. Taxed. So that's pretty cool. We just added a few more lines to our file. Let me remove that. Just so doesn't get too annoying going to save it and come back. All right, so we learned the upend. Let me just comment this out so that doesn't interfere with any of the other ones. Let's do a right this time. Now let's create some space year so we can see with the right, as you can imagine. Right file. And we'll just say that this file will be called by dot text very original naming by myself , and we'll just say, Sad to see you go and once again will taken air. And this error will say, if here console dialogue here. All right, so let's say that run the file or run the script and look at that by dot Text just got added. If we click on it, we have sad to see you go. We just created a new tax file. Very, very cool. But just so you know what happens if, let's say I miss Bell the read file and now it's held, not text. Well, if I run this, I'll get an error and you can see that the because it errors out, I get the error message error with a lot of ours. All right, a little bit of us Segway there, but just in case people were asking or you were thinking about that. All right. Who getting tired. So let's do one last one. And then I'm gonna tell you exactly why this is so cool. Um, the final one, we're gonna dio again. Let's make some space here is going to be the delete. So with the delete weaken do f s dot on link? I know it's so the name is a little bit off here but on link and will say that by text and notice that I was able to just Dubai dot tax here. But just to keep it consistent enologist say bye text with the dot slash before it. And with this one again, if there's any years Well, just log. Oops, I did have got to do the if perfect now Well, let's see what happens here and just for fun. We just at a console that log here after it's done deleting and will say conception because we're saying bye to the by text. Mind blown. All right, let's run this. I'm going to say and we'll comment out the right file here because you don't need to write it. We already have the by text. Let me save. And now if you look at the by tax, let's see what happens here when I run the script. Look at that. The by text was just removed. Inception just happened. Awesome. So that was very exciting for me. Hopefully was for you as well. But why is this exciting? Well, because now we're able to use programming in JavaScript outside of just Web browsers. And outside of just building websites and servers, what we can do now with this knowledge is we can make our lives easier. You can think of cases, maybe you wanna read an Excel file and there are things that you can use using read file and using NPM modules that you can read. Let's say columns in an excel and do some math. Or maybe you have an excel sheet with all these emails and you want to send out an email to , let's, say, 100 people on this list. But you also don't want to be caught spamming people by the Google filter, saying that hey, this account of spamming because they just sent ah 100 emails in two minutes well, using something like no do you can create perhaps something that every six hours sends out five emails. Another thing you can do. If he had a robot, for example, something similar to a file system. Instead of having reading from the file, he can read from the robot, maybe through wireless, maybe through wires, and get an input off some data that the robot has. Maybe it detected a cat well, using that input, you can do something. You can respond, maybe send you an email saying that the robot just detected a cat and send that email it, or send that hope it. And that's what we call input output, where you're getting an input from another source, another machine, and then you are also out putting something for consumption. That is really, really exciting because it opens up the world where you can create tools for yourself. You can automate things you can literally do anything that your mind can think of, and I know this is still early, and you're still at the beginning off your develop a courier. But this is the first step in into understanding how you can use programming to solve problems and make your life more efficient. Or maybe just a little bit more fun. So in the next video, we're going to do something fun. We're gonna use what we've just learned, and we're going to help Santa out on a coding challenge. I'll see you in that one. Bye bye. 11. Exercise: Santa's Node Helper: Welcome back. I have a fun little challenge for you. And this challenge comes from one of my favorite programming Web sites on the Web, and it's called Advent of Code. And advent of code happens every December. Programmers from all over the world doesn't matter, while language the right in you can do these problems with any language that they want and you're supposed to solve for 24 days until Christmas. These difficult problems using coat. So we're going to actually do something fun. Here we have advent of code from 2015. I know that's a little bit old, but I really, really like this question. I think it's gonna be really, really good practice. So I'm gonna leave for you this challenge and there's two parts to this challenge. So think of it as you need an answer to the first part and the second part. No, I'll share the link to this challenge so you can actually read all the rules, and you can even get the input for your puzzle right here. And you don't worry. That looks confusing, but once you read the question, you'll understand why that is. The exciting part is that in the next video. But make sure you don't want you before you finish it in the next video. I'm going to show you what I would do if I was solving this logic problem using programming . And this way you can compare why you do versus what I do doesn't mean that my way is correct. There's many, many different ways to solve problems when you're programming, but as a fun little challenge, you're gonna figure out the solution to this problem Using are at best module using node and using javascript. And then I'm going to show you what I do, and we're gonna see who's codus faster. And the way we're going to compare our code is we're going to do something like this inside of our function. Whatever that function, maybe you're most likely going to read the file. But they provide for you, which is this over here, right after you do that, we're going to say console dot time and we can give it any label we want. So legis say the fun challenge Now, Consul locked on time when we hit this line is going to start a timer, and it's only going to end when it sees the console dot log or time and and we have to give it the same input or the label because the first time we called it so fun challenge now this way. Well, this is what happens if we run it. So when we get a bit of an error because we're deleting this fall, which we don't wanna do that, let's clear and try that one more time. Fun Challenge took 0.319 milli seconds. Well, that was really, really fast, because all we're doing is really console logging. But using this, let's see how fast your function solves the problem. And then I'll show you how fast my solution solves the problem and we'll have a little bit of a competition. It's also you on that one. No, by 12. Solution: Santas Node Helper: all right. Hopefully everybody had a chance to solve the advent of code Santa's little puzzle. The house here. I'm going to show you now what I would do if I was reading this question or if I was looking at this logical problem, Which again is something that in interviews you get asked a lot. And in your day today, when you solve complex problems, they're usually the small chunks of logical questions that are asked and you want to solve . So I'm going to go through What I would do doesn't mean it's the only way. But what I would do to solve these problems, All right, By now you've all read the question and what we need to do. So after reading the question, I would get my puzzle input, which I have here. I'm going to copy all of this and right here I have my hasam node folder with nothing inside it. I'm just going to create a santa dot text file and in this text file or copy and paste the directions that well, we have no idea what's going on. Let me close that now, reading the question. The first thing I want to do is I want to make sure that I have a script file that I can run. All right now, before I start coding anything, everything in my head and used to make sense, and I like to keep things organized. So the very first thing I usually do is I comment and say that from reading the question. We know that there are two parts. There is Question number one, question number two. So we're only gonna focus on the 1st 1 which 1st 1 is what floor does Santa and up on. And the second question is, well, if we go here the first character that causes him to enter the basement. So we want to say, When does Santa first enter the basement? All right, so now I have everything clear, and we also know that there's a few rules. The rules are that this character means that it or not, it Santa should go up one floor. And I also know that this character is the opposite and should go down one floor. And I know this is silly, but it's really important for you to write things out and understand what you're doing. And why your goals are. We know that we want to solve this question using these parameters that we get from our input, which is, well, gibberish for now, right? So question number one always like starting it off with a nice function. And we'll just say question one and we think question one, I'm going to do our refile. So let's go to the top here and do const f s equals require fs All right? And we've done this before, so this should be fairly simple. It's fs read file. We're going to read the santa dot text file and the Santo Duck text file will get an error or data and within here want to ignore air for now, I'm sure it's gonna work, So I'm just going to say, const directions are going to be data dot to strength, and that in itself means that the directions variable now has the directions that we want. So let me just run that to make sure that it's all OK. And he saw over here that nothing sprinted because this function was never ran. So let's do that. We're going to say question one, let's run it. All right, looks like we're printing out all this information, which is exactly what we want. Those are the directions, and this is another thing. I like doing things step by step, making sure that it all works before I write everything out. And then, oh, something's wrong. But I don't know what's wrong. I go one step at a time, logically talking it out in my head to make sure that it makes sense. As I'm writing this, everything flows like I'm speaking. We have the first question we're reading File Santa and from the Santa text. We're getting the directions. All right, so what do we want to do next? Well, we saw in the output that these will it's just one big string, but ideally, we can split them. So if we split them, we can analyze each 11 by one like an array. We maybe we can map over an array. So sneaky way of doing this is we can just say cost directions. Ferree and this directions array will get split up into raise by doing split and splitting it just like that. And there's just a little bit of ah, shorthand, little trick. So again, if I console dialogue, directions, array. There you go. I have everything in an array. That's a lot of items in the array, but everything is split out individually now. All right, next step. So I have each array. So we want to read each one of these because each one equates to either up one or down one . And, well, we went out Map over this. Want to go over each one of them. But we're accumulating something, right? We're saying Juan, that if we have two floors up, that's two. If we go one down, that's wants where adding and subtracting constantly. So in that case, we can actually do reduce. So with reduce, I can say, const. Answer in this case will be directions array dot reduce and this reduce takes the first function. So the first parameter is a function, and this function takes the accumulator and I'll just do a C C. For now, just cause it's shorter and then the 2nd 1 is the current value. Let me make this smaller, shaken see, and this is a function that we're going to do some stuff here, but the second parameter is what we want to start off with in the accumulator, so we're going to start off with zero. So Santa's on floor zero on the ground floor within here. We can just say if current value, because reduce maps over each one of these items. And if the current value triple equals on, let's say this, which is up one floor. If that's the case, well, we can just return Accumulator plus equals one, which is shorthand for doing accumulator plus one. So this adds one to the accumulator. So if the first item is this little bracket here, it's going to be zero plus one. So Santa's gonna move up one level and then we'll say else if current value equals the opposite bracket, then we do the exact opposite, and we're gonna return accumulator minus equals one, so it's gonna go down one. All right, So just out of curiosity, let's run this and see what happens. Going to clear and run this one time and we get nothing because, well, we haven't said anything, so let's just console log. At the end of this, we have the answer. So let's just console dot log cancer and will say that the answer or we'll just say floor. So if I run this again Oh, I get a bit of a nearer And that's because I forgot a come over here selling me. Let's run that again. Let me clear. And I guess Floor 280. That's the answer. That's where Santa ends up. He ends up on floor 280 if he keeps following the direction until the very end. Very cool. So again, just out of curiosity, let's add time to figure out how long the stakes and we'll say Console that time. Whoops. Whoa. My auto tab is not working well today, and we'll say Santa time and this Santa time within this function told that we get the answer Well, say Sander, Time and fire on this. Our function runs 437 0.437 Mellie seconds. So pretty fast because not doing anything to too crazy, so curious why you got here. Keep in mind that this really depends on the type of the machine, the type of machine you're on, but again, pretty fun to think about how to structure your code. So it's first of all, it makes sense. It runs nicely, and also you want to make sure that it's efficient and looking at this. We're not doing anything too inefficient. All right, let's move on to question number two and question number two. Let's make space for this question. Number two Ask asks. When does Santa first entered the basement? So that is well, using this loop over here. Us. Santa starts to get direction. When does accumulator go into the negative number? Now I can simply copy and paste this into question number two and just maybe add an if statement here. Maybe I can say, if accumulator equals or is less than zero, then you know we can say console log the answer, and that works well. But again, thinking about the question this reduces going to map over everything. And you remember this is a pretty big array that were creating out of the directions. So if Santa on the first move goes into the basement, well and then we still go through every item in the array, that's a bit of a wasted time, right? So we want to think about the problems in ways that make sense to us and our efficient. And that's something again that you wanna practices. Does it make sense in your head? If you are supposed to do this manually, would you go step by step into through everything? Or would you just stop when Santa enters into the basement into the negative number? So let's find a better way to do. Question number two again with question number two, I'm going to say function question to and within here will say, Have us read file once again and this refile will read santa dot text again. This is the same as above. So I'm just going to do this quickly and the very first part, which is the directions and getting them into an array that's the same. So I'm just going to copy that again, getting the directions, making enter an array by splitting it. And now I'm going to add a little function that I think is better than reduce in this case . So I'm going to say the answer equals direction, array dot some and some. What it does is going to look through the array, go step by step, and if it finds something that matches is going to stop looping So with directions does some. I'm going to have the current value and this current value. So that is the item or the bracket that we're getting. So this current value again, we're going to do this. If steaming current value and current value, we're gonna add one or subtract one. So again, I copy and paste it on here. But again, we don't really have a C. C in this function and because we're not really using a reduce. But we do want to keep track of a counter to see when Santa's gonna enter the basement. So outside of the function, I'm going to say, Let accumulator let me just be more descriptive this time and will say zero. And this accumulator is going to get implemented based on the directions. All right, so using that, we'll see what my console log answer will me. So we'll say again. Basement entered that and we'll say, answer and let me just remove question one for now and just run. Question two must run this basement entered at true and we made a mistake here because what we want to do it from some is we want to return something we want to return when a goal is met. So at the end, we're going to say return accumulator. And when the accumulator is created, then zero Remember, return ends the function. We're going to say Stop whatever you're doing and then that's going to end the function. But we want to know when does Santa first enter the basement? So that is Ah, what number of directions does center and enter the basement. So we also need a counter. So this counter is going to be equal to zero, and I've missed a bunch of semi colons here, but that's fine. And we're going to increase the counter every time it goes through an item. And now the answer. Well, not this, but the answer is going to be the counter itself. So if I do counter, save right and let's run this And I actually made a mistake here because it's still zero because the counter is being increment ID after the return statement. So current value let's actually name this current heightened. It's a lot more descriptive current item. This is being returned before you even hits the counter. So in our case, unlike above, we don't really need the return statement. I want to save Run. And there you and the answer in this case is 1000 797. Awesome. So again to test it out. Let's use our son Santa time known to copy from above. And we'll just put it at the top for time and at the end for time. And let's see how fast that function runs we have again, quite fast. But if I did reduce, which in our case, that's what we use for the first question. So let's just go through that. We see that well, the first round of Santa damn wishes. Question one is Let me just at a que want in here so we can see and que to. I'm gonna add that to make sure the labels match. Let's do that again. Now it's a lot better. All right, so, um, we see that question one definitely long runs low longer than question, too, because the first time around, we have to look through everything the second time around. It's a lot less time just for fun. Again, how is like testing our assumptions? So if the first direction was to go downstairs. Let's see what happens. All right, so that's a little bit faster than before. Not by a lot, cause we're still kind of doing a bit of calculations, but still a lot faster than going through this many items. Just in case you're wondering why, in this case question to end it before or ended before question one. And not so in the other cases again. Remember that read file is a sickness which everyone returns first, gets returned. All right, Hope you have fun with the challenges. If you've enjoyed this, I recommend you keep going through the advent of code and hopefully as a group with our community. When December rolls around, we're already too. Follow Advent a code for this year I'll see in the next one public.