Node.js: Getting Started

View non-AMP version at androidpolice.com

Course Overview

Course Overview

Hello, everyone. My name is Sam are bona I love coding and I love teaching people to goat. I work at agile labs dot com, where we create interactive content to help people learn coding. Welcome to this. No, Jess. Getting started course from Pluralsight note is an amazing run time. It's simply a game changer. Once I got comfortable working with note, I never looked back to anything else I used before knows I'm excited to show you how note is going to make your life as a back end developer so much easier. I mostly write code in this course, and you should do to. Learning to code is mostly a practical experience. Try to do and redo the examples I'll present in this course and try to expand their scope and challenge yourself with every piece of knowledge that you learn. Some of the topics that we will cover in this course include the what, Why and how of No Jazz. A review of the modern JavaScript Concepts notes Ruppel and Command Line interface Notes Patterns. Global's and Utilities Notes Package Manager and PM Working with common Jess Modules, Notes, Concurrency and Event Loop. Working with web servers and working with the operating system. By the end of this course, you should be comfortable creating and executing code for note, understand the big pictures of the runtime and build simple back and applications with IT. I hope you'll join me on this journey to learn the basics of the excellent no just run time in this getting started course at Pluralsight.


Course Introduction

Hello. Thanks for tuning in to this course. My name is Sam URL Bouna. And this is the no just-as getting started course at Pluralsight. This is a beginner, of course, for the nauseous from time. I won't be assuming that you know anything about node. But I will be assuming that, you know, the basics of programming and a little bit of the JavaScript language itself. This course has a module about modern JavaScript. But I do not cover the basic concepts of the language there. If you've never worked with JavaScript, IT for this course might be a bit challenging for you. And if you get yourself a bit more familiar with the JavaScript language itself, this course will be a lot easier to digest if you know JavaScript. But you don't know the modern JavaScript changes that happened in the past few years. That's okay. This module will get you covered. If you're expecting this course to make you a professional. No developer, I need to get your expectation straight. This is a short course toe on Lee. Get you started on your path to learn. Note. It's just a first step. No, it is a big framework, with many built in modules and concepts, which you need to learn. But they require much longer time and bigger effort. This course is designed to help you get ready for that. Here are the main topics covered in this course, and you can see them here in order. First, we'll go over some of the core features in note and how to execute scripts and work with the command line. Then we'll do a review of the modern features in JavaScript that you can execute in your note yesterday. After that, we'll talk about notes. Package manager npm. Then probably the most important part about this course is when we start talking about modules and note and how note handles slow operations. Then we'll go over some examples about working with web servers and note both natively and with external tools. And finally, we'll talk about how to work with the operating system files on commands. Ah, lot more features in the note. A P I will not be covered by this course. For example, this course will not cover C plus plus add ons, buffers and streams, modules like Crypto Z lip, DNA's Net and di Gram and many others that I classify as Mawr advanced concepts. The good news is that I created an advanced note course here at Pluralsight is well, so after finishing this getting started course, I think he'll be ready to take a deeper dive and explore the other advanced concepts that I cover in this advanced no Jazz course. Here I am recording this course on a Mac book. If you have a Windows machine, things are going to be a bit different for you. Note itself is a bit different on Windows than it is on Linux and Mac. You might run into problems that I don't. If you do run into problems that block your progress in this course, please don't hesitate to ask for help in the discussion section of this course. If you have a modern Windows machine, one option that might work a lot better for you is to install the Windows subsystem for Linux. This option will give you the best of both worlds. You'll have your Windows operating system running Linux without needing to reboot so you can work a Linux file system with your Windows editor, for example, which I think is great I've tested this option, and I can confidently say that this will probably be the future of writing code for node on Windows. No, it is usually deployed on Linux machines and production. So by using a Linux environment on your Windows machine, you'll be closer to the way your-app ligations are running in production. And that's always a good win. I often get complains that my Pluralsight courses are a bit fast, and it's hard for people to keep up. This is true, and this course will be no exception. It's not that I am a fast talker. It's the fact that these courses are tightly edited with no breaks. Ah, lot of content is intentionally jammed into a short course. That, however, does not mean that you can't manually give yourself breaks. The most important button in the Pluralsight video player is probably the pause button. Use it often. For example, every time I ask question, pause the video and think of it every time I use something that you've never seen before, pause the video and Google IT. Rewind and watch things many times if you need to. If you're used to the pace and breaks of workshops, you'll find the pace here much faster. The pause and rewind _______ are your best friends. Also, in some of the modules of this course, I'll be presenting you with challenges, positive video and do these challenges. The best way to learn is really to do. I'll be also asking a lot of questions in this course, and I'll answer these questions right after. But I want you to imagine yourself in an interview for a job about no just-as and treat these questions as if they were your interview questions. Try to answer them first before you listen to me answering them.

What Is Node?

Okay, so you can probably answer this question, but this is a first step course in notes, so let me start at the very beginning. What is no just-as here is probably the simplest definition of note. It's JavaScript on your back end servers before note. That was not a common or easy thing to do. JavaScript was mainly a front end thing. This isn't really a complete definition, because note offers a lot more than executing JavaScript on the server. In fact, the execution off JavaScript on the server is not done by note at all. It's done with a virtual machine. PVM, like V eight or chakra note, is just the coordinator. It's the one who instructs the VM like V eight to execute your JavaScript so note is better defined as a wrapper around the VM like V eight. I'm going to use the term V eight in this course because that's the default VM in note. But you can totally run note with other VMS if you need to, so when you write JavaScript or note, note will pass your JavaScript to-be eight v eight will execute that JavaScript and tell note what the result is and note will make the results available to you. That's the simple story, but no, it is a bit more useful than just that. Besides, the fact that enables us to execute JavaScript on a server, which is done through a seamless integration with V eight Note comes with some handy built in modules providing rich features through easy to use asynchronous APIs in the next module. We'll talk about that and a few other reasons why developers are picking know just-as over many other options when it comes to creating servers on their back ends.

Why Node?

we learned that note allows us to easily execute jobs shipped good on servers, but this is not really impressive. It was even possible to do that before ____. So let me put the big question out here. Why? Note since you're watching this course now, you probably know reason or two. Why? No, it is a great thing to learn. Let me make sure everyone knows all the reasons before we commit to this journey. So besides being an easy way to execute and work with JavaScript on the server note comes with some feature rich, built in modules. This makes it a great platform for tools, not just a platform to host back in servers. But here's the big deal about the modules that are packaged with load. All of them offer asynchronous AP ice that you can just use and not worry about threads. Yes, you can do a synchronous programming in note. Do things in parallel without needing to deal with threads, which is probably the biggest benefit of using or in time like note. And if the built in packages were not enough for you, you can build highly performing packages using C plus plus note is JavaScript, but it has first class support for C plus plus add ons, creating dynamically linked, shared objects that you can use directly in note. Of course, you can also write your add ons and JavaScript, too, if you want. Note also ships with a powerful do ______, which I'll show you how to use in the last module of discourse. No, it also has some handy generic utilities that enhance the JavaScript language and provide extra AP ice to work with data types, for example, and we're not done. In fact, these last two points on this slide is, in my opinion, the most important ones. And this is why this course will have full modules dedicated to these last two points. I wrote an article about the exact topic of Why note? With a lot more details around the last two points in the slide. Let me go over this article quick and summarize it here for you. This article is about why react Developers love note, but it really applies to just note in general, why JavaScript Front end developers in general love note So note is a platform for tools. So even if you don't want to host your whole application in note. Note is a great platform for tools and the reason It's great because you have a lot of options. You have so many tools out there because no, it was the first major job script execution engine that ships with a reliable package manager, which is called npm. We did not have a package manager for a long time in the JavaScript world, so npm is actually very revolutionary in here because it changed the way we work and share JavaScript. And no, it was the enabler here. Because npm is part of note, npm is basically the world's largest collection of free and reusable code. You can make a feature rich no delegation just by using code that's freely available on npm. Npm is a reliable package manager, which comes with CLI that we're going to explore and that CLI makes it really easy to install third-party packages and in general, share your own code and reuse your own code. And the npm registry, where the packages get hosted, has so many options, and by so many I mean hundreds of thousands of options off free tools that you can just install and use in your system. The other big thing about Node is that it comes with a reliable module dependency manager, which is different than npm. This module dependency manager is also another thing that we do not have in the JavaScript world. More accurately, we did not have for a long time because job script today has what's known as app JavaScript modules. But these modules, despite being part of the language officially, are still a work in progress. They're still not completely supported by all implementations nodes. Common jazz dependency system has been available since node was released, and it opened the door to so much flexibility in how we could JavaScript. IT is widely used even for JavaScript that gets executed in the browser because node has many tools to bridge the gap between its common just system on what browsers console work with today, npm, along with common Js, make a big difference when you work with any JavaScript system, not just the JavaScript that you execute on the server or in the browser. If, for example, you have a fancy fridge monitor that happens to run on JavaScript, you can use note for the tools to package toe organize to manage dependencies and to bundle you code and ship it to your fridge. Note also is not just for hosting JavaScript servers, but it's also a very good option to do so because of its non blocking asynchronous nature, which you can use without dealing with threats. This is the main point that made no different than any other system that was popular before. Newt. Note comes with first glass support and easy a piece for many asynchronous operations, like reading or writing files, consuming data over the network and even compressing and encrypting data. You can do all these operations in node a synchronously without blocking the main execution threat. This works great with V eight because V eight itself is single threaded, and this is true for both note and browsers. You only get a single precious thread toe work with, and it's very important to not block IT. For example, in your browser. If your website blocks that single thread for, say, two seconds, the user cannot scroll up and down during these two seconds in note. If an incoming SD to-be connection to your Web server was handled synchronously, rather than a synchronously that will block the single thread. And your whole web server cannot handle any other connection while the synchronous operation is active. And that's a big deal. No, the asynchronous AP ICE also work great for cloud applications in general because a lot of these operations are asynchronous by nature. And, of course, by using note, you are committing to the flexible JavaScript language, which is used on every website. Today. It is the most popular programming language, and that statement will continue to be true for decades to come. And despite its problems, JavaScript is actually a good language today. With note, you get to have a single language across the full stack, use jobs shipped in the browser and use it for the back end as well, which means less Centex to keep in your head and Les Mis takes over. All This also means that you can have a better integration between your front and code and you're back in code. You can actually share code between these two sides, and using job script on the back end also means that teams can share responsibilities among different project projects. Don't need a dedicated team for the front end and a different team. For the back end, you would eliminate some dependencies between teams. The project can be a single team, the JavaScript people. They can develop a _ _. _. They can develop weapon network servers and they can develop rich interactive websites. Note, of course, has a few cons, which are, interestingly, the same pro points if you just look at them with different bias. For example, the non blocking nature is just a completely different model of thinking and reasoning about code. And if you've never done it before, it is going to feel weird. At first. You need time to get your head wrapped around this model and get used to it. And the big npm registry with so many options means that for every single thing you need to do, you have many options to pick from, and some people hate that. You need to constantly research these options and make mental effort to pick the better options. These options usually have major differences, and also npm enabled shipping smaller and smaller code, which means you need to use MAWR and more packages. It's not unusual for a note application to use 300 or more packages. This is both a good thing and a bad thing, depending on who you ask. I think it's a good thing. Smaller packages are easier to control and maintain and scale, but you do have to make peace with the fact that you'll be using a lot of them. Smaller code is actually why note is named node. In note, UI build simple, small single process building blocks, notes that could be organized with good networking protocols to have them communicate with each other and scale up to build large distributed programs. Scaling a node application is not an afterthought. It's built right into the name.

Some Analogies About Node

I love thinking about real life analogies that compare with the coding world. One of my favorite analogies about coding in general is how it can be compared to writing cooking recipes. The recipe in this analogy is the program, and the cook is the computer. In some recipes, you can use ready items and tools like the cake mix that you can use to make cupcakes, and that's specially shaped pan that makes it easier to create cupcakes when compared to coding. You can think of these ready items and tools for recipes to including and using a package of code written by others in your own code note. And it's powerful. Npm package manager has their place In this analogy, npm is a place where you can download code written by others. Within this analogy, you can think of npm as the store where you purchase the ready items and tools. You just bring them to your project with a simple command, and you can think of no jazz itself as your kitchen as it allows you to execute lines in your coding recipes by using built in modules like the Oven and the sync. Imagine trying to cook. Without these built in modules in your kitchen, that would be a lot harder. And just because you have these built in modules in your kitchen, that doesn't mean you have food ready to consume. Note is your kitchen by itself. It's not enough, but it does make your task to write useful code much more easier throughout this course. You'll hear me use the term call back all the time, so let me quickly tell you about it. Call Back is just a fancy term for a function. In note. We call the function a callback function if Node will call it back for us at a later point in the time of the program. This is done through an asynchronous method. Here's the simple callback function, which usually received data as its argument, and we just pass its reference here to some asynchronous method, and that asynchronous method will get the callback invoked when the data is ready. I have another analogy for you about call backs when you order a drink from Starbucks in the store, not in the drive thru. They'll take your order and your name and tell you to wait to be called when your order is ready. After a while, they call your name and give you what you asked for. That name you gave them is the callback function here. They called it with the object that you requested the drink. So let me modify this generic example of a callback to demonstrate the Starbucks example. The callback function is the name you give during your Starbucks order. It's a function that be called with some data, which is you already drink when you place your order. That's an asynchronous method, because your order will take some time and they don't want to block the order. And Q. While your order is getting prepared, that's why they'll call you back. And that's the pattern of callback functions in note. Now, modern JavaScript in Modern Note started adopting another pattern for asynchronous programming, which we call promises, and the promise is a little bit different than a callback To understand promises. Imagine that you ask someone to give you something, but they give you something else. Call it a mystery object. They promise you that this mystery object might eventually turn into the thing that you originally asked for this promise. Mystery object can always turn into one of two possible forms. One form is associated with success and the other with failure. This is like if we ask a chicken for a chick and the chicken gives us an egg instead, that egg might successfully turned into a check or it might die and be useless if you like analogies like these, I have a lot more of them, and most of these technologies are really related to note. For example, see the reactive programming one and the errors versus Exceptions one.

What You Get When You Install Node

follow this video for instructions on how to install. Note. If you've successfully installed note, you should see the following three commands available globally in your system. First, the note command itself, which, if you run it without any argument, you'll get into this interactive program where you can type and execute JavaScript. Here's a quick test of how modern your notice. I typed the test for you right here under this GitHub. Just go find this code and then copy this line here the first line and paste it into the nodes. Interactive session. Don't worry. If you don't understand this, it's just a test of your note capabilities. If this line was executed successfully without any errors like it did for me here you have a good version of note. If you get an error here, you should upgrade your note for this course. This course has a modern JavaScript module where I'm going to explain the modern concept this simple line is using. You can also test if your note has the new promises. AP Ice. Using these two calls in here, you tell that promise. If I should return a function like this and require F s dot promises should return an object of the full F s, a p I just like this. Also, if you want to use Eckman script modules with node, the import statement should be available. And it should give this exact specific error in the rebel here because we can't use it in a rebel, but it's available for modules. So if these calls are giving you errors or undefined objects, it will be a good idea for you to upgrade your note before starting this course. The other two global commands that you should have our npm and MPX. You get these as well. When you install node, we'll talk about these commands in the course module dedicated for npm. If you see these commands working successfully for you, you can skip the rest of this installation instructions video to install node on windows. You can simply download the installer from the No, just the order website and granite Locally. This way you'll be installing note natively on the Windows operating system. But remember what I said about node on windows in the overview video note. Natively on Windows is not really ideal, but if it's your only option don't let that stop you. If you were able to get a Linux subsystem working for you on Windows great. All you need is to commands. Let me show you how to find them here real quick in this downloads page scroll and find the article about installing note via a package manager. Click that you can also just Google this exact title here. If the U I of the note website has changed, the Linux distribution that you used in your subsystem is probably open to hear. So click on that link and under the section here, you'll find lines to install the recent version of note. So these are the two lines that you need in your subsystem or Linux in general. You should also invoke this other line here about build essentials just in case you need to install any Native Addams in the future. On Mac, you can download and install no directly. But if you're already using the excellent Homebrew package manager, you can just use that All you need is brew install note, and this will give you the latest note. If you don't have homebrew on your Mac, you should really take a look at it. It's pretty cool. If you have an older version of note running through homebrew, the command you need here is brew upgrade Note. Just like that, there is another option that works on both Mac and Linux, and that is envy M node version manager. I like this option because it allows you to run multiple versions of note and switch between them using a simple command. If you find yourself in a situation where you need to work on a project that use different versions of node, N. V. M will help you here. That's it for installing note. Don't forget to make sure these lines work for you on your new note you just installed.

Example Files

on the course reviews light. There are references two folders associated with the modules of this course. These folders can be found on get hub or under the exercise files section. Here is the good help repository that I'll be using throughout this course. It will give us starting points for code templates and let us focus our time on concepts rather than wasting time typing simple scripts. This report is hosted under GitHub dot com slash gs complete slash n gs and GS here is not getting started. You can see the different folders for the different modules right here. The same content of this ripa is also available under the exercise files on the course page. If you don't have access to get up, your first step is to clone this repo locally to your machine. To clone this repo, copy the NGS repo. You're Ellen here and type the following command in your terminal Get clone the repo your URL. This will create a directory named NGS under your current working directory so seedy into this new NGS And in here you can see the list of numbered folders. Let me open up An editor here on this repo. So within the top level folders, which are associated with modules in the course you'll see folders and files representing videos of the course module. In order. However, some of the course videos will not have folders, and some folders here might have multiple files representing the examples we are going to cover in its associated video. The files are usually numbered in the order off their example in the video and all these files in the NGS Repo is your starting point for each exercise we're going to go through in this course. One thing I'd like to point out before we begin. This course has many modules. We use the word module here to describe a section in the course. The word module is also heavily used, with note to refer to a file or folder of code. To make this a little bit less confusing, I will say course module every time I refer to a section of the course, So let's jump to the next course module and get you properly introduced to the wonderful nauseous Runtime

Getting Started with Node

Node’s REPL Mode

in this getting started module will explore the node command and a few global features like timers, and the process objects. If you type in the note command without a script for it to execute. Note will start a rebel session rappels stands for read evil print loop. And it's a very convenient way to quickly test simple JavaScript and no documents. You can type in any job script here in the rebel, for example, a math, random call just like that. And then you press, enter and note, will read your line evaluated, print the result and then go back to waiting for further lines. This is where the rebel got its name. Read a line evaluated, print its output and loop until the user exits the rebel. Note how the print step happened automatically. We didn't need to add any instructions to print the result. Node will just print the result of each line you type. This is cool, but keep in mind that some lines will not have any results at all. The note rappel will print undefined in this case. For example, if you define a variable like this, let answer equal 42 and you enter, you'll see undefined. This is because this is a statement in JavaScript. It's not an expression, it does not have any output. And this is why the ripple printed undefined as the output of this statement. Don't let that confuse you. On the other hand, let's type out an expression. For example. Three. The number equal equal three. The character. This is a bullying expression, by the way. Quick question. Do you think this expression evaluates to true or false? Well, this is one type of question that can be easily answered inside a node Rebel. You type it real quick and enter, and there you go. This is true. So this line was a JavaScript expression, and the ripple printed its result for us. Sometimes the expression that you need to test might need multiple lines. Let me clear this rebel session, and I do that by pressing control and l. This clears the session, and let's see an example of multiple lines. Say that you want to define a function that generates today's date and test it out. You'll start with the function name. Name IT today and then begin with a curly brace, right. You can hit Enter here. The notes. Rebel is smart enough to detect that your line is not done yet and it will go into this multi line mode for you to type more so we can type. Return New date Semi Colin hit. Enter again, then the end Curly brace and enter. And now note figured out that this good can be executed and it did. Executed. We can now use the Today function in the rebel session. This rappel multi line mode is limited. For example, if online three you realize that you made a mistake on line one, you cannot go back and edit line one. In addition, you cannot type out multiple expressions in the same multi line session. Luckily, note has a more featured editor right here. Inside Durable. You type in adopt editor to open it up, and when you do, you can type as many lines as you need. For example, you can define multiple functions or paste code from the clipboard. When you're done typing, you hit control D to have the ripple evaluate your code. All the functions that you defined in the editor will now be available in your rebel session. The dot editor Command is a rebel command, and there are actually a few other commands. You can see the list by typing the dot help command the dot break command, or it's not clear. Alias lets you get out of some weird cases in the rebel session. For example, when you paste some code in notes, multi line mode and you are not sure how maney curly braces you need to get to and executable state, you can completely discard your pace IT code by using at dot break command. This saves you from killing the whole session. To get yourself out of simple situations like this, the Docker exit command exits the rebel, or you can simply press control de the dot load and dot save commands can be used to generate and use external note scripts inside Europe. All this could be a great time saver. Here is a fresh rebel session. Let's say I started typing in this rebel session. I defined one function, and then I defined another function, and then I define the third function, and now I have some history in this ripple session, and what I want to do is I'd like to save all these functions to an external file, to maybe review them later or maybe commit them to get. All I need to do is dot save and give it a file name. I'm gonna call IT M seven Duchess. And now, if I inspect the content of M seven Dutch us, this file will have all the lines that we previously typed in the rebel session, which is really cool mawr. Importantly, if later on we started a brand new proposition and we wanted to redefine the functions UI previously defined in M seven judges, all we need to do is use the dot load command with M seven Digest as the argument. A node will load all the lines in the file and evaluate them. And now we have access to the functions and variables defined in that file.

TAB and Underscore

I need to emphasize the importance of the tab key. If you're not familiar with this powerful key, you're in for a treat. The tap character itself is not a very useful one, but the tap key is the driver off a very powerful feature called TAP Completion. You might be familiar with that feature in your code editor, but I'd like you to also be aware that it works inside note rubble as well. A single tap in the notes. Trouble can be used for auto complete and a double tab, which is pressing the tab key twice can be used to see a list of possible things you can type from whatever partially typed string you have. For example, if you type the characters see and then double tap on that, you'll see all the possible keywords and functions that start with C. You could be defining constant or clearing a timer. And if you single tap on something that matches on Lee, a single option will be out of completed. For example, crypto here is the Onley cured that begins with C. R. So if you single tap on cr crypto will be auto completed, this is by the way, is not about being lazy about typing the whole thing. The usefulness of this tap completion is about avoiding typing mistakes and discovering what is available. This latter point is important. For example, say I want to know what a P I functions and properties I can use on the array class. I can type Ray. Note how I used single tap for that. But then I can type the dot character and double tap after that. And there you go. These are all the functions on properties that can be used from the array class. This also works on objects. If I have an array object inside this rebel session, I can use the same dot and then double tap trick to get a list of all the methods available on this object. If you can't remember the name of the method you need, this list is helpful. The tap completion discover ability works anywhere. Do you remember the special document? While you can see them by double tapping on a single dot, This discover ability also works on a global level. If you double tap on an empty line, everything that is globally available appears This is a big list, but it's a useful one. It has all the common global's in the JavaScript language itself, which you're probably familiar with, like Ray number string and object classes and built in libraries like math and Jason on some top level functions. The other Global's you'll see in this list are the ones that are available in the know Dreamtime itself. A few of these are truly global in note, like the buffer class, the process object and the various functions to set and clear timers. The lower case variables here, for example, DNA's Net cluster and Ashley to-be. Those represent the built in modules and note these our notes powerful libraries that you get out of the box, not how these are available directly here in the ripple. But when working with a regular note script, which will do next, you'll need to require these modules to be able to use them. One of the useful rebels features that you can use here is the underscore variable. This is similar to the dollar sign question mark feature In bash, IT stores the value of the last evaluated expression. For example, say that you executed a math, random call. And after you did, you wanted to put that same random value in a constant. You can do that with the underscore because it automatically stores the last value you can use the underscore variable in any place where you use a job script expression. I could do something like const random equal underscore to place that same last random value in a constant

Executing Scripts

here is note. Hello World Example. This simple script represents a simple web server. You don't need to install anything to run this script. This is all nodes built in power. Don't worry about figuring out what's going on in this script just yet. We'll get there eventually to execute this script with note. You just specify the location of the script as the argument for the node command. You can actually see the location of this script within the Projects folder right here in the corner for my Adam editor here. And I can also click this region here to copy the full path for this file. So now I'll go ahead and paste this full path right here after the Note Command, and this will execute the file. As you can see, it reported back, that server is running the script location that you specify for a note. Command can also be relative. So if I'm inside this one getting started one Executing Scripts directory and I specify node one Hello world, just like that node will look for the file in the current working directory if the script that we're executing has a running task like a Web server listening for connections, for example, then Node will continue running. Note that if the script does not have a running task like this other script here that just prints a message node will execute this script and exit immediately after that. And what process exiting is a normal thing In a note, Cluster node will not idle and use resources unnecessarily okay, back to the simple web server script and were executed again. So now this simple web server script is running and its task is active. IT listens. For all the SD to-be connections, however, this note process will Onley use V eight when there are actually to-be connections. Otherwise, V eight will remain idle. Let's decipher this simple web server. The first line here is using the require function. This is the first thing you need to learn about nodes internal. The required function is what you use to manage the dependencies off your programs. You can use require to depend on any library. Whether this library is a built in one like Azure to-be here or if it's ah third-party installed library. This program here depends on the built in HD to-be module. It's the module that has the features of creating a Web server. There are many other libraries that you can use to create a Web server, but this one is built in. You don't need to install anything to use IT, but you do need to require IT. Remember that when we were in nodes rebel, this library was available immediately without needing to require IT. This is not the case with executable scripts like this one. You can't use any dependencies without requiring them first. This line here creates a server constant by invoking the create server function on the HDTV module. This function is one of the many that are available under the http module AP. You can use it to create a Web server, and IT accept an argument that is known as the request listener. This is a simple function that node will invoke every time there is a request to the created web server. Remember this argument. As a listener, this server will listen to requests, and it will invoke the listener function for each request. And this is why this listener function receives the request object as an argument. It's named wreck here, but you can name it. Whatever you need. The other argument this listener function receives named raise here is a response object. It is the other side of the request connection. We can use this object to write things back to the requester. It's exactly what this simple web server is doing its writing back using the DOT end method and the Hello World String. We'll learn about the dot end method later in this course, but it can be used as a shortcut to write data and then end the connection. The create server function on Lee creates the server. IT does not activate IT. To activate this web server, we need to invoke the dot listen, function on the created server. Dysfunction accepts many arguments like what OS port to use for this server? The last argument here is a function that will be invoked once the server is successfully running on that port. This example just logs the message to indicate that the server is now running. This listen function is what actually keeps the note process running. It's the task that will keep the note runtime busy and not exit while the server is running. If we go to a browser and ask for initially to-be connection on local host with the port that was used in this script 40 to 42. In this case, we will see the hello world string that this example had in its request. Listener, go ahead and try to change this line and return something else. You will need to restart the note process to make the change work. Just kill the process with control. See used the up arrow to get the last executed command and execute that again. If you refresh the Web browser now, you should see the newly returned strength. When we build a full web search, for example, I'll show you how to avoid needing to restart the server every time you change something, because this will be an annoying thing to keep doing manually. This hello World script uses the common GS module management system. Every script that uses this require key word here is classified by note as a common JSON module. Note also supports the JavaScript module management, and you can use that in two ways, either by naming the file with the dot M. J s extension, which I'll show you right here or by setting the whole project to use app JavaScript modules. I'll show you that option in the npm course module. So let me copy this one. Hello world dot Js file keeping the content as is and given IT at dot m j s extension. This time, if you try to run this script node will complain about the require keyword because it understood that this is an Acma script module because of its extension. And with Acma script modules, we don't use the require keyword at all. We use the import keyword Let's fix it. This is the problem line To fix it, we use the following import then the name of what you want to import. In this case, it's HD to-be then from the location of the module you're importing or just the name for built in modules like SDK to-be here. So import something from module, path or name, and this will now work. There's also another Centex we-can use with import which is called named imports. Let me show you that you see, this creates server method that we're using here through the SD to-be object. Well, we can import that particular method using this curly brackets Centex and then use it directly in the code. So instead of importing the whole HD to-be object, we used a named import and Onley imported what the script uses.

Working with Timers

some of the popular global functions in a browser environment are the timer functions like Set time out and set Interval? No, Jess has an A P I for these functions as well and exactly matches the browsers. A P I. These time or functions can be used to delay or repeat the execution off other functions, which they receive as arguments. For example, this code uses set time out to delay the printing of this greeting message by four seconds. The second argument to set time out is the delay in milliseconds. This is why we are multiplying for by 1000 here to make it into four seconds. The first argument to set time out is the function whose execution will be delayed if we execute this script, normally with the note command note will pause for four seconds, and then it'll print the greeting and exit after that note that this first argument to set time out is just a function reference. It does not have to be an in line function like this. For example, this good here will do the same job, but it uses a function defined before said Time out. Note that if the function that we pass to set time out receives argument like this example here. Argument 123 and more. Then we can use the remaining arguments in set time out to pass these arguments to the delayed function once it's executed with set time out. Here's an example. Take a look at this code and try to figure out what it will do. The Rocks function, which is delayed by two seconds except a WHO argument and our set time out call, relays the value Pluralsight as the WHO argument. Executing the script will print out Pluralsight rocks after two seconds. Time for a challenge. Ready Using what you learned so far about set time out. Print the following two messages after their corresponding delays. Print the message Hello after four seconds after four seconds, then print the message. Hello after eight seconds after eight seconds. This would be an easy challenge without constraints, but we are not here to learn just the easy stuff. I have a constraint for you. You can Onley define a single function in your script, which includes in line functions. This means many set time out calls will have to use the exact same function. Okay, pause here and try it out. I really hope that you will try to do these course challenges because trust me on this. It is the best way to get comfortable with what you're learning. If you just watch, you'll learn. But it will be harder for you to retain and improve. You do that when you start pushing your limits and put yourself outside your comfort zone. Here's how I'd solve this challenge. I've made the one funk receive DeLay argument and used that delay argument in the printed out message. This way, the function can print different messages based on whatever delay UI pass to IT. I then used the one funk in to set time out calls, one that fires after four seconds and another that fires after eight seconds. Both of these set time out calls also get a third argument to represent the delay argument for the one funk. Executing this script will print out the challenge requirements. The first message after four seconds and the second message after eight seconds. But what if I ask you to print the message every four seconds forever? While you can put that time out in a loop node offers the set interval is well, which would accomplish exactly that. Just use a set interval instead of set time out. In this example, this code will print its message every three seconds. Note will print this message forever until you kill the process with control C. Another cool thing about these timers is that you can cancel them with code. A call to set time out returns a timer ID, and you can use it with a clear time out call to cancel that timer. Here's an example. This simple timer here is supposed to fire after zero milliseconds, making IT immediate, but it won't because we are capturing the timer ID and canceling IT right after with a clear time out call. When we execute, the script note will not print anything, and the process will just exit. By the way, there is another way to do set time out with zero millisecond the time or a P. I has another function. It's called set immediate, and it's basically the same thing as a set time out with a zero millisecond. But we don't have to specify a delay here. It's an immediate thing. We'll see a practical case for this function later in the course and just like clear time out. There's also ah, clear interval, which does the exact same thing but for set interval calls. And there is also a clear immediate which does the same thing for set immediate calls. So as you can hopefully see from this example, executing something with set time out after zero millisecond does not mean executed right away, but rather it means executed right away. After you're done with everything else in this script, let me make this point clear with an example. Here's a simple set time out call that should fire after half a second, but it won't right after defining the timer UI Block note synchronously with a big loop. This is one with 10 zeroes in front of it, So this is a 10 billion takes loop, which basically simulate a busy CPU note can do nothing while this loop is thinking. This is, of course, a very bad thing to do in practice, but I'll help you here to understand that set time out DeLay is not a guaranteed thing, but rather a minimum thing. This 500 millisecond here means a minimum delay of 500 milliseconds. In reality, this script will take ah lot longer to print its greeting line. It will have to wait on the blocking loop to finish first. Let's do one more challenge on timers. Print the message. Hello World Every second, but on Lee five times after five times print the message done and let the note process exit and you cannot use a set time out call for this challenge. Little hint. You need a counter here. Okay, you can pause here. Hopefully, this was an easy one. I initiated a counter value as zero and then started as an interval call, capturing its I. D. The delayed function will print the message and increment the counter each time inside the delayed function. And if statement will check if we're at five times by now. If so, l Brent done and clear the interval using the captured interval constant. The interval delay is 1000 milliseconds. In this file here, I've put a couple more challenges for you to practice timers. I will not solve these challenges here to keep the course short, but I included the solutions in this same folder in the course Rebo

Node’s Command Line Interface

so far. We used the note command in two modes. To start a ripple with no arguments and to execute the script by using a single file path argument. The Note command, which is often called the CLI, also has options which make it work differently. For example, the desk V option makes it up with the version of the note runtime and the DASH. P Option makes IT execute a string and print out its result, which I find super useful. For example, if I want to see how Maney CP use this machine has, I can use a call to the built in OS module, which has a function called CP Use and I can do dot lengthen that to see the size of the returned array. Similarly, here's another one liner to see the version of the V eight used in the current node installation. There are many other options. You can see a full list by using the dash H option. This could be a big list so you can pipe IT on the less command or its windows equivalent to Pagine ate your way through this list. Take a look at these options and familiarize yourself with them. Don't memorize anything except for the handy dash p one. But just be aware of all the things that you can do with this CLI. One of these options also opens the door to the options of V eight itself. Let's explore that list using node dash Dash V eight Dash options Pipe that on less as well. Node will report all the V eight options that it supports. These options get past to-be eight, for example, to make V eight. Always execute your job, script and strict mode. You can pass the dash dash. Use strict option. I wish this one had a default value of true but unfortunately, does not. The V eight options are a really big list, and it's mostly for advanced use. But let me tell you a few more things about it. You'll see some options that begin with the word harmony. These flags usually control the features that are still being tested. You can use them by including their flags, but just know that they are not final yet. You'll see many options for tracing. If you need V eight to give you more debugging power, you can make it up, Put more information. Some options control how v eight behaves and also control its limits. Other options will report information or give you control over what's usually not possible without them. Do a quick scan on this list, but usually if you think you might find helpful option here, you can grip this list to search for it. For example, you can grip for in progress to see all the in progress harmony flags for this particular note version. In addition to all these flags, the note CLI also supports some environment variables that you can use to change the process behavior. You can see this list at the end of the dash H output. For example, this node debug environment variable instructs core modules to print out any debug information they have. If we execute the Hello World script with no debug set to SD to-be, which is the core module used there, then on each incoming connection, that HDTV module will print out some debugging messages. Most node libraries, including the packages that you'd install on use support a note debug flag. You can give this environment variable. A comma separated list of the modules for which you want to enable debugging another hand. The environment variable is this note path. One by default. Node has certain paths. IT used to look up modules you require in your code, and you can use this environment variable to override that. These are the built in environment variables, but you can have your note process use any other environment variables as well. Let's talk about that next.

The “process” Object

you can use the note command with custom environment variables. For example, we could do something like Val one equal 10 Val to equal 20. Note. No commas here, then continue to execute a note script like this in the notes script. We can access the values in the environment variables using the process object, which has many properties. But the one that you can use for this purpose is the end property, which is an object that has all the end of properties available through the operating system. Like user here. It also includes the one we just customize, like Val one and Val to-be. You can export environment variables prior to executing a script, and note will read those as well. For example, instead of this one liner, UI conduce something like Export Val, one equal 100 export Val to equal 200. And then we can execute this script normally, and it will pick up our 102 100 values. This is a handy bridge between the operating system and the node process. You can use it to communicate dynamic configuration values. For example, if you want your script to run on development, port 40 to 42 but in production you wanted to run on for 80. Instead, you can use process the end to make the port dynamic and control IT on different machines. There is another way to pass information for the execution context of the note process, and that's through the process. The Ark via Ray. This array will have an item for every positional argument you specify when executing the node script in order. For example, if we have a note command to print process the RG using the handy dash p CLI option All the arguments after this command will be set in the resulting ray as strings. Even if you pass numbers, this ray will always assume strings. The first item here in the resulting array is the location of the Note Command. And if we're executing a script, the second item in this array would be the script name. But in this case, we're not executing a script. So the remaining items in this ray are the arguments that we passed to the Note command and they're all strings in this array. This is a cool feature, but I think I prefer the process. The end of method because I get to name the past values there with RG, we'd have to do more tricks to accomplish this. Named values feature Other properties you should be aware of on this special process object are the standard input output stream. There are three of them STDM for input STD out for output and STD air for error messages. These control the communication channel between the note process and its operating system execution environment. We've been actually using them under the hood when you use a console dot log line that line right to the STD out stream. In fact, you can accomplish the same functionality of console the log by using a process The STD out the right line just like this. S t d n can be used to read information from users. Here's an example to do that. The STD Io objects are all streams, which is a topic that we are yet to explore. But the gist of it is that we use events and methods to use these streams. In here we are listening for a readable event and using the read method to read a chunk of data and then we print out the same chunk to STD out, making this effectively an echo utility. IT will echo everything you type two IT. There are multiple ways to consume and benefit from these Io streams and streams. In general, for example, this same echo example can be done using the excellent pipe function that's available on readable streams like process that s t d n UI pipe readable stream into a rideable one like process that STD out using the argument for the pipe function. And this makes the exact same echo utility. We'll have a bit more to learn about streams later in this course, but for now, just make a mental note that streams are awesome and you should utilize them in every possible way. Notes. Process Object can also be used to terminate the process or do something when the process is terminated unexpectedly. Here's an example of that. This code has a timer that will fire after two seconds, and it will call the exit function on the process object. This will manually terminate the process and make note. Exit as note is exiting the process. It looks for any listeners registered on the exit event. We have done exactly that in here. Which means right before note exits, IT will execute this function to print out this message. Because of the nature of asynchronous code in node, this hello line will be executed first. Then the timer will go next and the exit listener will fire. This simple example demonstrates the power of note asynchronous nature and its event with Adala. Gee, we will learn more about that in the concurrency module of this course.

Wrap Up

I hope you are now excited about node. This module has been just a teaser about the many powerful features that come built into the note or in time. This includes things like its powerful rebel on CLI, and it's built in libraries like etc. To-be, which we use to quickly create a Web server. It also comes with plenty of customizable options and a built in bridge to the operating system. Through the process object, however, UI Onley scratched the surface in this module. There are so many other things that I want to show you. But before I do, let me make sure that you are familiar with the modern JavaScript features that I'm starting to use and will continue to do throughout this course. This next module will be exactly that. A _____ course on all the modern JavaScript features that were added to the language since 2015 and are now natively available in your node environment. Features like template strings, arrow functions, classes, block scopes, de structuring promises with a sync weight and more. If you're already familiar with these features, you should skip this next module

Modern JavaScript

EcmaScript and TC39

JavaScript is a very different language than it used to be just a few years ago. IT JavaScript, which is the official specification that JavaScript confirms to has improved a lot in the past few years after a rather long period of no updates to the language at all. Today, the JavaScript Technical Committee, which is known as T C 39 makes yearly releases of JavaScript and JavaScript engines like V eight, shortly followed by implementing the new features introduced in the EC JavaScript releases. This has started with JavaScript 2015 or its other commonly known name s six. Since then, we've had yearly releases named ES plus the current year. Some of these releases were big and others were very small. But the language now has a continuous updates cycle that drives mawr innovative features and phase out the famous problems JavaScript had over the years. Anybody can propose features that they think should belong to the jobs of language. The T C 39 committee has a five stage process to filter and finalize the features that are considered for the language. A feature starts at stage zero, which is when anyone proposes anything to the committee. And if the proposed feature has a clear problem and a clear case for its need and someone is willing to back it up through the process, it gets labeled as Stage one. Once the proposed feature has an initial spec document, it gets labeled as Stage two draft. At this point, there is a strong chance the feature will be part of the language when the spec of the feature is finalized and the designated reviewers of the future signed off on it. The proposal is labeled Stage three candidate. At this stage, the feature is queued for more tests, and the committee will accept this back text into its main specifications. Repository, which gets the feature to Stage four Finished and that feature will be included in the next year. Lee Release of Atma Script In No, Jess, you only have access to features that are finished and are already part of the language. However, V eight often has harmony flags for you to experiment with candidate and even draft features. Sometimes you can also use the babble compiler to write many of the in progress features in JavaScript and have babble compile it to the good old supported JavaScript before you take your code to production. Babel is popular on the front end because many browsers air usually slow to add support for all the new features in the language, including the finalized ones. And Babble offers an escape hatch for developers to use the latest and greatest without risking their code not being compatible with older browsers. In this course, I'll only use features that are natively available in Nadia's, including many of the modern features that started becoming available since 2015. In the next, few videos will go over some of these features and learn the value they bring to the language.

Variables and Block Scopes

first up, let's talk about variables and block scoops. Here is one of my favorite JavaScript trick questions. Is this a valid JavaScript line of code? Testing it in a no trouble seems to work fine, which means it is valid. So the question is, now, what did it do? These are nested block scoops. UI could write code in here for a equal 42 and then access a right after and it would be acceptable. JavaScript does not really care about the spacing or new lines in here. A block scope is created with a pair of curly braces just like this example here. This also apply to if statements and four statements as well. These also get their own block scoops. Block scopes are a bit different than function scopes, which are created for each function. You can see one difference when using the var keyword to define variables. Variables defined with far inside a function scope are okay. They don't leak out of that scope. If you try to access them outside of the scope, you can't. As you can see here, we could not access the result variable that was defined inside the some functions scope. However, when we define variables with bar in a block scope, we-can totally access them outside that scope afterwards, which is a bit problematic. And here's one practical example of that. This four loop has an index variable that takes from 1 to 10. You can access that variable inside the loop normally, but you can also access the same variable outside the loop. After all iterations air done, the value of I hear will be reported as 11 and that's a bit weird. This is why the more recommended way to declare variables in modern JavaScript is by using the let keyword instead of the var keyword. Because when defining variables with let, we won't have this weird out of scope y-access problem. If we replace this far here with let and do the same, test will try to access let after loop. We need to start new note session here, paste in the code, try to access I. After that, it will tell you that I is not defined, which makes sense because we're outside of the school where it was defined. So this is much better. Block scopes like function scopes can also be nested like the trick question that we started with this is a nested block scope within each level of nesting. The scope will protect the variables defined in it as long as we use the let keyword or the Const keyword, which behaves in the good way, like the let keyword UI use. Const. When the reference assigned is meant to be constant because references assigned with CONST cannot be changed, not how I'm saying references and not values here because Constant does not mean in mutability, it just means constant reference. But if the reference is foreign object, we-can still change this object just like we can do with functions that receive objects as arguments. So if the variable defined with Const. Is a scaler one like a string or integer, you can think of it as an immutable thing here. Because these scaler values and JavaScript are immutable. We can't mutate the value of a string or an integer in JavaScript. And because we used costs with these scaler values, we can't change the reference either. However, placing an array or object in a const is a different story. The cost will guarantee that the variable is pointing to the same ray or object, but the content of the array or object can still be mutated. So be careful here and keep that in mind to accomplish In mutability for objects, JavaScript offers a freeze method, but IT Onley freezes the first level of that object. So if you have a nested object within the first object, that nested object would not freeze. If you want to work with immutable object, I recommend the immutable JSON Library, which has an A P I that will guarantee objects in mutability. Variables defined with CONST are much better than those defined with let for scaler values and for functions, because you get a guarantee that the value did not accidentally change. Looking at this good example here and assuming that between the first and last line, there is a big program on the last line, we-can still confidently say that the answer variable still holds the 42 value because the code ran without problems while for the same example would let we would have to parse through the code to figure out if the answer variables still hold the 42 values. If you need a variable toe, hold a changing scaler value like a counter, for example. Then using let is okay. But for the most cases, it's probably much better for you to stick with using Const.

Arrow Functions

There are many ways to define a function in JavaScript on the modern specifications introduced a new way. Arrow functions away to define a function without typing the keyword function, but rather by using an arrow simple like this, this shorter Centex is preferable not only because it's shorter, but also because it behaves more predictably with closures. So let me tell you about that. An error function does not care. Who calls IT while a regular function cares very much about that. A regular function like X here always bind the value for its this keyword for its collar. And if it didn't have an explicit collar, irregular function will use the value of undefined for its vis keyword and error function. On the other hand, like why here, not caring about who called it will close over the value for the this keyword for its scope at the time it was defined, making it great for delayed execution cases like events and listeners because it gives easy access to the defining environment. This is important, so let's take a look at an example in any note module like this one. The top level this keyword is associate it with the special exports object which I'm going to tell you more about soon. But in this example, I'm just giving this exports object a label toe. Identify it because it's empty by default and here I am printing the value for the exports. Object for you to see testing this script with note command. You should see an object with I'd exports. Now I prepared this tester object, which defines to similar functions where in both I am printing the value for the this keyword function. One is defined with the regular Centex, while function to is defined with the arrow Centex. When function one is called, it's this keyword will be associated with its collar, which in this case is the test our object itself. And this is why you see the printed value for the this keyword in function. One representing the tester object itself. However, when function to is called, it's This keyword will be associated with the same this keyword that was available in the functions scope when it was defined, which was the modules, exports object, the one I gave a label. As you can see here, this is a big benefit when working with listeners in no jazz, and it's why you'll see me using error functions all over the place. One other cool thing about error functions is that if the function on Lee has a single line that returns something, you could make it even more concise by removing the curly braces and the return cured altogether. You can also remove the parentheses around the argument if the function receives a single argument, making it really short. This syntax is usually popular for functions that get passed to array methods like map reduce and filter and functional programming in general.

Object Literals

you can create an object in JavaScript with a few different ways. But the most common way is to use an object literal. Here's an example of that. This is a lot easier than doing something like new object, which you can if you want to. Literal initiation is very common in JavaScript. We use it for objects, raise strings, numbers and even things like regular expressions. The object, literal syntax, supports a few modern goodies. Here's a simple example where this object defined to regular properties if you need to define a property that holds a function, you can use this shorter Syntex with object literal. Of course, if you need an error function, you can still use the regular property. Centex Modern Object Liberals also support dynamic properties using this Centex, which looks like an array literal. But don't confuse it with that. JavaScript will evaluate what's within the square brackets and make the result of that the new property name. So, assuming we have a variable named mystery defined before this object, and I'm gonna go ahead and copy this code into a new rebel session, and now here is your JavaScript interview question. What is object that mystery. It's undefined because this mystery property was defined with dynamic property. Centex, which means JavaScript, will evaluate the mystery expression first on whatever that expression. Evaluated, too, will become the object property. In this case, the object will have a property answer with the value of 42. Another widely popular feature about object liberals is available to you when you need to define an object with property names to map values that exist in the current scope with the exact same names. If you have a variable named pie and you would like O B G to have a property named pious well holding the same value as the variable pie instead of typing the name twice like this, you can use the shorter Centex by admitting the second part in this shorter Centex is equivalent to what I had before. Objects are very popular in JavaScript. They are used to manage and communicate data, and using these features will make the code a bit shorter and easier to read.

Destructuring and Rest/Spread

the de structuring Centex is really simple, but I've seen it confused many people before. Let me make sure that does not happen to you. The structuring works for both arrays and objects. Here's an example for objects using the built in math object in JavaScript when you have an object like math and you want to extract values out of this object into the enclosing scope, for example, instead of using math up, I would like to just have a constant named pi toe. Hold the value of math up I, which is easy because you can have a line like this. Format that pie in another one for E. If you need the same for E and so on with the de structuring Centex, these three lines are equivalent to this single line IT these structures the three properties out of its right hand object and into the current scope. This is useful when you need to use a few properties out of a bigger object. For example, here is a line to the structure, just the read file method out of the nodes FS module. After this line, I can use the read file method directly like this. These structuring also works inside function arguments. If the argument passed to a function is an object, instead of using the name of the object every time you want to access its properties, you can use the these structuring Centex within the function parentheses to these structure, just the properties that you are interested in and make them local to that function. This generally improves the readability of functions. So here we have a Circle Area function, which expects an object as its argument, and it expects that object to have a radius property on. We're de structuring the radius property out of that object and using it locally in the function. If we call this Circle area function with an object like circle, it will use its radius property inside for its calculation. Let's go ahead and test that you'll see the Circle Area calculation working as expected. These structured arguments can also be defined with defaults like regular arguments. If, say, I'd like to use the default value of two for precision property here. Let's define second IOPS shins argument for this circle area function and the structure precision out of that argument to use it in the functions body. If I'd like to use the default value of two for the precision property, I can just use the equal sign here after the structuring precision. And that means default for precision, if not specified, will be, too. I can also make this whole second argument optional using an equal sign after the de structuring Centex. The same call here will use an empty object for the second argument of the function, and then it will use the default value of two for the precision property that is now used in the function. Of course, if you called the circle area function with the second argument that has a precision property, that value will be used inside the function. As you can see, this de structuring feature offers a good alternative to using named arguments in functions, which is a much better thing that relying on positional arguments de structuring, whether you do it in function arguments or directly with variables, also works for a raise. If you have an array of values and you want to extract these values into local variables, you can use the items positions to the structure, their values into local variables just like this. Not how I used double-click. Mama's here to skip the structuring. The third item injury, the D structured variable fourth here will hold the value of 40. This is useful when combined with the rest operator, which has an example here. By using these three dots, we are asking JavaScript to the structure on Lee one item out of this array and then create a new array under the name Rest of items toe. Hold the rest of the items after removing the first-one. Let's test that so first here will be 10 and rest of items will be an array of 2030 and 40. This is powerful for splitting the array, and it's also even more powerful when working with objects to filter out certain properties from an object. Here's an example of that. Say that we have this data object, which has a few temp properties, and we'd like to create a new object that has the same data except for temp one and tempt to-be we-can D structure temp one attempt to and then use the rest operator to get the remaining properties into a new object called person. Just like the three dots of rest. You can use the three dots to spread one array or object into a new array or object. This is useful for copying arrays and objects. You can spread the items in an array into a new array like this example. New area here will be a copy of the rest of items array that we d structured above, and similarly, you can also spread the key value pairs of an object into a new object. Like this example. The new object here will be a copy of the person object. Note that these copies air also shallow copies. Any nested objects or arrays will be shared between these copies. Don't forget that.

Template Strings

template strings are one of my favorite new features that were introduced to the JavaScript language a few years ago. Let me tell you about them. You can define a string in JavaScript, using either single quotes or double quotes. Thes two ways to define string. Liberals and JavaScript are equivalent. Modern JavaScript has a third way to define strings, and that's using the back tick character on my keyboard. It's right above the tab. Key strings defined with the back tick character are called template strings because they could be used as a template with dynamic values as they support what we call interpolation. You can inject any dynamic expression in JavaScript within these dollar sign curly braces holders. So, for example, we can use Matha random here, and the final string will have the value of the expression included exactly where it was injected in the string. If you test this string and note, you'll see a random value every time you do it with template strings. You can also have multi lines in the strings, something that was not possible with the regularly quoted strings. Back text look very similar to single quotes, so make sure to train your eyes to spot template strings when they are used in examples


JavaScript offers many programming paradigms and object oriented programming is one of them. Everything in JavaScript is an object, including functions. Modern JavaScript also added support for the class. Centex A class is a template or blueprint for you to define shared structure and behavior between similar objects. You can define new classes, make them extend other classes and instantiate objects out of them. Using the new keyword, you can customize the construction of every object and define shared functions between these objects. Here is a standard class example that demonstrate all these features. We have a person class and the student class that extends the person class. Every student is also a person. Both classes define a constructor function. The constructor function is a special one that gets called every time UI instantiate an object out of the class which we do using the new keyword. As you can see here we are instantiate ing one object from the person class and two other objects from the student class. The arguments we pass here when UI instantiate these objects are accessible in the classes constructor function. The person class expects a name argument. IT stores the value on the instance, using the whiskey word here and the student class expects a name and the level arguments. IT stores the level value on its instance, and since it extends the person class, it'll call the super method with the name argument, which will invoke the person class constructor function and store. The name is well. Both classes define a greet function that uses the values they store on each instance on the third object, which UI instantiate IT from the student class here. We also defined agreed function directly on the object. When we test this script, 01 will use the greet method from its class. The person class 02 will use the great method from the student class and 03 will use its own directly defined greet method.

Promises and Async/Await

note is event driven. Most of the functions that you will be working with in note return promises, and you'll have to consume them using the promise syntax. With that, then and catch, However ah more preferable way to consume promises is using the new A sync await Centex, which makes your promise consuming code a bit more readable and easier, especially when you start dealing with loops and other complexities. Here's an example code that is consuming a promise object using the regular promise. Centex. Here we have a simple fetch function that reads and https response for a URL. Don't worry about the implementation of this function. Just notice how IT returns a promise object. This is the modern alternative to using callbacks for the A sync nature of dysfunction. To consume the fetch function, we use the dot then Centex, which will expose the data available after the A sync action. Alternatively, we can also consume any promise using the A sync await feature as seen here. We use the keyword await before the promise and that will give us access to the data available after the A sync action. We can use this data directly after that wait line just like this, which is a lot simpler than callbacks and using dot then as well. However, to make this away feature work, you have to wrap your code with a function labeled with the A sync keyword, and then call the function to execute the A sync action. Testing this good Now the same fetch promise will be consumed twice, once with the regular dot then Centex and another time with the new A sync await Centex the A sync awaits and taxes definitely easier to read, and it will make your life especially easier if you need to work with promises that depend on each other or promises that need to be within the loop.

Wrap Up

this module was a quick review of the modern JavaScript features that were introduced to the language in the past few years and are currently available natively in note. We've talked about block scoops and how they are a bit different than function scopes and how it's wise to use the let and Const. Keyword within them. We've seen how error functions are different than regular functions. We've explored the modern ways to work with object liberals and talked about de structuring and the rest spread properties. We saw how to work with template strings and how to create and use classes, and finally saw an example of consuming promises with regular promise. Centex on with the A sync Await us well. In the next module, we'll explore the npm tool. Npm is notes package manager, and it has a website hosting hundreds of thousands of note packages. We'll explore the npm tool itself and talk about some of the most popular npm packages out there

NPM: Node Package Manager

What Exactly Is NPM?

Welcome back. Let's talk about npm nodes. Package Manager npm enables JavaScript developers to do three main things, share their code with others, reuse their own code across projects and use code written by others in their projects. So npm is basically all about code sharing and reusability. If you have a piece of JavaScript code that you'd like to share with others or just reuse in other projects, npm is the tool you need to help with that. But npm is also about compose ability off bigger applications using smaller packages you can use. Others work to complete yours so you don't have to start from complete scratch. In general, npm is an asset for any team that is working on any job script project. It makes it easy to separate and manage the different versions off good. The npm project runs at npm G s dot com. This is the site that hosts the many useful npm packages that you're going to love and appreciate. It also hosts a lot of empty and useless packages because there is no quality control here. Anyone can publish anything and we are about to publish something in this module. But I'll try to make it a bit useful. Npm is the official note package manager. The npm project started with a small set of notes scripts to manage common tasks around folders that contain code for node. And IT sense evolved into a fully featured package manager that it's super useful for all job script code, not just note. If you browse the registry of the npm packages that are hosted on npm JSON dot com, you'll find packages that are for node and packages that are libraries and frameworks meant to be used in a browser or a mobile application. If you dig deep enough, you'll even see examples of APS for robots, routers and countless other places where JavaScript can be executed. A typical note project will have tens, if not hundreds of npm packages. Some npm packages represent big frameworks like express or sales. Some provide utility functions like load ash here. Some just provide useful libraries. The request package here is an example of that Many npm packages are small and specialized around one problem and focused on how to solve that problem. Well, let's give credit where credit is due. Npm simply revolutionized the way JavaScript developers work, the life of a JavaScript developer was much harder before npm. Npm is a very important part of note, and a good understanding of how it works will prove to be very valuable for you as a no developer. So what exactly is a package manager and why do we need IT? Let's actually start with um, or basic question. What is a package? The name package is what npm uses toe label. The bits of reusable good A note package is basically a folder that contains scripts that can be run by note, which is to say that any folder that has some JavaScript code in it is basically a node package. Another name that is commonly used to describe a code folder in note is module. Some modules are built in note, so npm is not needed to manage those but most other modules that you'll be using our external to note and npm is what we can use to manage them when you have a project that has a lot of these good folders that we are going to start referring to as packages. From now on, you'll need to manage them somehow, especially when these packages start depending on other packages. And when you start working with multiple versions and sources of these packages, that's where npm can be helpful. When developers talk about npm, they could be talking about one of many things they could be talking about. The npm GS website that hosts a public registry of the many open source npm packages. This website provides a few graphical features, like searching for packages. For example, every package page has some meta information about the package, like the number of downloads and other information managed by the package. If the package has a read me file, it'll be displayed here is well. Developers could also be talking about the npm command line interface. The CLI tool that we can use in our projects to manage the package is this tool has many commands that you can see here. We are going to learn a few of them in this course module. Npm is also the name of the company npm Inc that hosts and maintains the npm Registry and CLI Tool and is doing more business around the npm Registry and tool. They offer private repositories and mawr enterprise level services. Let's now talk about the npm CLI tool that gives us this global npm command

The NPM Command

as a note developer, you will be working with the npm command a lot. This command comes installed with node itself so you don't need to do anything to install it. If you have not installed, you should have the global npm command installed as well. You can check the version with dash V. Npm gets updated more frequently than note. So sometimes you might need to update npm itself separately from note to get the latest release. You do that using the command npm install dash G for global npm. Yep. You can use npm to update npm If you get an e access air here, that means you most likely installed node itself with some admin privileges. You can use pseudo in that case, or start a whole terminal with admin privileges on Mac OS. If you install node through homebrew or npm, you usually don't need to sue do any note or npm commands. If you are facing the access error, you can also fix the npm permissions so that you don't have to run. Npm would suit you. Let's quickly explore the first command of npm, the one that we just used install to do that I'm going to create a test directory test npm CD into that and run npm install. By the way, install has a shortcut. You can just do npm my, which is cool. And we're going to install one package called Express. So this npm install command is our client that just downloaded the package from its source, which by default is the npm just that calm registry itself. But you can configure the command for other sources. And after IT downloaded that package, npm placed the package in a special folder under the project named Node Modules. So this is the process that's known as installing a package. But there's nothing magic about it, really. It just places the package under this Node Modules folder. Note itself is designed to use this note modules folder by default toe. Look for any packages IT needs to use. When note needs to require a package like express here, it does not communicate with npm at all. It just uses the note modules, folder and packages that were placed inside that note modules folder. Did you notice how when I installed the express package here, npm warned me that this folder does not have a package. Jason, file this package. That Jason file is important. So let's redo this example with a package that Jason File. I have a folder in the three npm folder here called one npm command. And this folder has the package that Jason file. So let's see d into this folder and redo the npm install express command and note what happens to the package that Jason file. Did you see that? The package that Jason file had a new section here. This is the section where npm is documenting this new dependency for this project Express. Not only that, the npm installed process will also take care of installing any sub dependencies for the main installed package. Take a look at what you now should see under the Node Modules folder. Although we asked npm to install a single dependency express, npm installed many other dependencies. What exactly are these? These are the packages that express itself depends on. And since we made our project depend on express, these other packages are now in the projects. Sub dependencies. Okay, so let me quickly review what happened when we invoked the command npm install Express. Npm first created a new Node Modules folder because that folder did not exist before the first npm install will do that. Npm then downloaded express package from npm just dot com and placed it under the newly created Note Modules folder. IT then modified the package that Jason file to document this exact dependency and the version used for this dependency. And it also created a package dash lock Jason File. So let's talk about these two files. Package that Jason and package lock that Jason.

The package.json and package-lock.json Files

the package that Jason File is the one file that you'll see in every npm package. It's adjacent file that can be used to provide information about a package, and it's required by npm. This file is mostly modified by the npm command itself, but in a few cases you'll need to manually edit this file as well. In the previous example, we started with a simple package that Jason file that only had the required properties name and version. The name often npm package is it's unique identifier. If you need to publish this package, that name has to be unique and not used before across the whole registry. The version Property is a semantic versioning string. We'll talk about this string in the next video. When we installed the express dependency, npm automatically modified our package that Jason and added a dependency section documenting the version of Express that it used. Here is the package that Jason file for the Popular Express package. As you can see, this file includes meta information about express things like description, license and keywords. But the most important information in this file is the dependencies section. These are the packages that express depends on. And this is the same list of packages that we got when we installed expressed locally in the previous test. This is really the most important benefit off the package that Jason file. This file makes the building off the project. Dependencies are reproducible task. This means by sharing this package that Jason file with other developers or with build servers, the process of building the project dependencies on these other machines can be automated through the dependencies section off the file. Here, let me show you how that works. With a local example, let me add one more dependency in the one npm folder example here. This time, let's add the load ash package. The command that we need here is npm Install load ash. Npm is now downloading load ash and it just placed it under the note modules folder and updated the package that Jason file to document this new dependency. Now, the one npm folder right now has three things. The package that Jason file the other package lock Jason file and the Node Modules folder. Now, Usually, when you share your project with other developers, you don't share your note modules folder This is a big folder with code written by others. It does not belong to your teams. Get Repo, for example. So what your team will get when you share this project is just the Jason file. So let me remove this note modules folder to simulate that. So a team member just pulled this code. They now have the package that Jason file and to build their version of note modules. All they have to do is run the npm install command without any arguments. Just like this, this command will install all the dependencies listed in package that Jason along with their sub dependencies. In fact, thanks to the package lock Jason file, they will get the exact same versions. Even for the sub dependence History, for example, expressed depends on this bites package here that was installed when we ran the npm install command. Let's assume between the time that you added the express dependency and the time a team member pulled your code to use it, a new version of this bites and PM package was released. Your team member will not get that new version. When they run npm install, they are going to get the exact same version that you used because of package locked Jason. So the version of bites that was used here is 300 If you look at the content of this package, lock that Jason file. You'll see information not only about this project's direct dependencies, but rather the whole dependency. Three. For the project search for Bites, for example, you'll see how the exact version off the bites package is included here, and you'll also understand how bites was added to the project because it's a dependency of body parts. Er, which is a dependency of one of your top level dependencies expressed in this case while adding dependencies to package that Jason when you install them, you can also tell npm that a dependency is on lee a development dependency, which means it is not needed in a production environment. To do that, you're in the same npm install command, but with the Dash D argument D for development. For example, let me install the node mon package with the Dashti argument Here. You'll notice how npm added this node mont package under a new section in package that Jason, this time it's Dev dependencies. This is where you should place things like you're testing framework, your formatting tools or anything else that you use on Lee while developing your project. Now let's quickly take a look at the help page for the npm Install command, and you do that using npm. Help install. In here, you'll see all the usage patterns and the options that you can use with the npm installment and one of these options that you can see right here is the dash dash production flag. Or you can use the note environment variable and said that to production on what that will do is it will completely ignore your death dependencies, because these are development dependencies, so you don't need them in production. This is handy because this note Mont package is not something that you need in production. It's on Lee Use is in development. Do automatically restart node whenever a file is saved in the project. Notman is one solution to the problem that you need to manually restart node when you make changes to a file and it's a good compromise in development environment. But it's totally not needed in a production environment before we move on to the next topic, which is this semantic versioning string that we've been seeing in package that. Jason, let me show you a command you can use to automatically create a package that Jason file for a brand new project. So let me create another test folder here. I can use the make Directory command here on this machine on. I'm gonna call this my project and C D into IT. So this is a completely empty directory. Now, instead of manually creating a package that Jason file, you can run the npm in IT. Command. This command will ask you a few questions about your project and use your answers to create an initial package that Jason file for you. It tries to use defaults from your folder. For example, if your project is already a get rebo, we'll figure that out and include the repo. You URL You can also run this command with Dash dash. Yes, to just use the defaults instead of interactive lee answering questions. I'll do that for this example. Check it out. It created a package that Jason file with the name of this directory and initial version and this scripts section, which is an important, one that we're going to talk about in a few videos, and it's a very good one. But first, let's talk about these little version strings and understand the meanings of these elements.

Semantic Versioning (SemVer)

npm uses semantic versioning or some ver for short when it's time to update packages. Every package has a version. This is one of the required information about a package. That version in npm is written with the same ver format. The somber string is basically a simple contract between a package author and the users of that package. When that number gets pumped up to release a new version of the package, December communicates how big of a change to the package itself. Will this new release be The first number, which is called the major number, is used to communicate that breaking changes happened in the release. Those are changes that will require users to change their own code to make it work with the new release. The second number, which is called the Miner number, is used to communicate that new features were added to this release, but nothing major. All the changes are still backward compatible, and it's safe for users to install these minor releases, and they will not require the users to change their code to make it work with these releases. The last number, which is called the Patch number, is used to communicate that the release on Lee contained bug fixes and security fixes, no new features and no breaking changes. You often see a few different special characters before the versions. Strings in the package that Jason file these special characters represent a range of acceptable versions on are put to use when you instruct npm to update your dependency tree. For example, the told a character means that an update can install the most recent patch version. Remember Patches, the third number for the version of string on the screen here. It means npm can install any version that starts with 1.2 and is greater or equal to 1.2 point three. So a 1.2 point four version would be okay, and so would 1.2 point five or anything in that class. However, at 1.3 point zero version will not be used. So basically, this version range string is equivalent to one point to point X, where X is greater or equal to three. On the other hand, a caret-symbol in front of the somber string is a more relaxed constraint. It will get the package updated to the most recent minor version. Remember, Minor is the middle number. For example, carry IT. 1.2 point three here will match any one point x point. Why, where X is greater than or equal to two and why can be anything so you might get a 1.30 or 1.4 point five, for example. But npm will not update all the way to 2.0. I'll admit this might be confusing at first. Just remember that Kelda is for safe patch level updates, whereas caret-symbol more relaxed minor level update. Npm has a site that may make understanding this a bit easier. It's hosted here at some vered npm jess dot com. You can pick a package to see all of its available versions, then enter Arrange string to test for load ash, for example. IT alga 4 16 3 matches all patch level updates that start with 4 16 and has the patch number greater than or equal to three, while caret-symbol three will match what the tell diversion matched. But it will also include all the 4 17 versions. You might find it easier to use the X notation, for example, your version range string can simply be 4 16 x or even for the X, the tilde and carrot or helpful in communicating the exact version arranged started with I think some ver is great and responsible. Npm developers should respect IT when they release new versions of their code. But it's good to treat what it communicates as a promise rather than a guarantee, because even a patch release might leak breaking changes through its own dependencies. A minor version, for example, might introduce new elements that conflicts with elements you previously thought are okay to use testing. Your code is the only way to provide some form of guarantee that it's not broken.

Installing and Using NPM Packages

you have two options. When it comes to installing an npm package, you can install it either locally or globally. When we worked under this one npm command directory, all the three packages that we installed under this folder here were local. This is the default behavior of the npm Install Command. It'll just installed package locally under the project where you run the command. If the package is to be used within a node folder, basically, if you need to use it just for one project, you should probably install IT locally. I'd say 99% of the packages that you use should be installed locally. The only exception is when you need to install global tools. For example, create react app is a package hosting a tool react. Developers use that tool to well create a fully configured react application. This is an example of a package that's usually installed globally. You don't need to be in a specific directory to use this tool. You can use it anywhere. Also, once you're generated, react application is running. You are not really depending on the create react app tool itself anymore. You still depend on other packages related to create react app, but not on the package hosting the command to install and update packages globally, you add the Dash G flag, which is short for global. Once a tool packages installed globally, it's command will be available for you to run from anywhere, so for create react app. UI, npm install dash G, create react app And once a tool package is installed globally, it's command will be available for you to run from anywhere. The commands a package add to your system are listed right here when you install that package. So this create react. App. Command is now a command that I can run from anywhere, regardless of whether the package is installed globally or locally. Once it's installed, you can require IT from any node script under this to usage folder. Here we have a simple, empty package that Jason File. Let's install the load ash package locally. Remember how to do that npm install load ash and that's it that will install load ash locally under the two Usage folder and place that package under the Node Modules folder. Let's take a look under the note modules folder. Load ashes there and note how this package has no sub dependencies at all. The Onley package in our dependency three right now is load ash now within the current folder, we-can require the load ash package from any file. Here's a test that does exactly that. This test DGS file requires the load ash library and then uses its some function to some, the integers in an array, and I'll app. Put the result after that. Since load ash is already installed under the noted Modules folder, this file will run fine and output. The result. Now try to run the same file after deleting the note modules folder. So RM dash R F note modules, all of it. And now you'll find out that if you try to run note test duchess, you'll find out that you can't run this file load. Ash is no longer available for node to use. The Note Modules folder is simply the connection between npm and ____. You can actually place the load ash dependency under the parent folders, Note modules folders, so the note Modules folder doesn't have to be in the exactly actually where you are. Node will check all the parents for their own Note Modules folder so you can basically make a directory in your home directory called note modules just like that. And that directory would satisfy all the dependencies for all your projects. But really, this is not a recommended approach. If your note script requires load ash like this load, ash should be a local dependency under the project's main Note Modules folder. And the version you install should be documented in Package that Jason, so that all members on the team have a similar experience working the project dependencies.

Creating and Publishing an NPM Package

I think we're ready to bring out the big guns. Well, actually, this is a lot easier than it sounds. Let's create and then publish an npm package. Try to do this exercise with me on your own. Pause the video as needed and matter what I do. I've included a test file under the exercise files right here under the three Create Package directory. The goal is to make this file work and output what's expected, As you see here in the comment. So if we execute this file right now, it will not work because the frame print package does not exist. This is the package that we will be creating in this line. We're requiring this package and capturing the top level a p i of this package as the print variable. And then we're using the print variable as a function call. So the top level a p I in the package that we need to create should be a function. And here is the expected output. IT just prints the message in the argument in a frame of stars. All right, so let's start from a make direct recommend now. Usually you need to name the package as the string that we are using here to require so make directory frame print. So under frame print, we need to create new file. Let's call this file index Duchess. Now the name index the jazz is a bit special in note and npm by default when you require a folder note will look for an index the Js file under that folder which will work in our case. So just to test this index that yes, let's place a console log statement here and just say testing. So let me actually split this file in the editor here. Okay, so we've got this index suggests file under the frame print directory on we have the index dot Js file that is under the test directory, which we're going to use to test the frame print directory. Now to get this line here to work, this frame print package should exist under the note modules folder inside the test folder. We don't have that. We don't have a note modules folder inside that folder for testing purposes. Instead of using this line, we-can require the adjacent frame print directory using relative paths. So instead of requiring this directly from note modules. We-can say Let's go up one level and then require frame print from the same level as the parent of this test folder where we're testing with that, we can run this index dot Js file under the test folder, and it will require the frame print that we are testing right here. All right, let's test that So node test index Splunk-ES and you'll notice right away that we are in business. The console logline is now showing up in our test. Very good. We're still seeing a problem that says print is not a function because we did not export any A p i yet. So instead of console lock testing, let's go ahead and export an A p I. Now in a note module, you can change the A P I using the exports special objects so I could do something like a is 42 in here. However, if you need to change the top level export, you need to use the module. The exports equal notation. So our top level export here, which were capturing in the print variable, is a function. So let's go ahead and do a function here I'll name dysfunction. Print dysfunction receives a single argument, so we'll call this argument message now, inside this function, let's console log testing from function and let me go ahead and run the command again and make sure testing from function appears and it does. And you'll notice that the air about print not being a function is gone now because our top level A p I is now a function. So now all we need to do is to make this function output the message within F Star of frames. For that, we can use a few console log statements so we can do stars and we'll do another one just like that. And inside the frame, Well, just console log the message just like that. Let's go ahead and test no test the up, but now matches what was expected here. Okay, so this is a very simple package, and really, the logic hair doesn't matter. What matters is we now need to make this package work without our modification to the test here, Basically, by doing that and I'm going to assume that we're done developing this simple package, we need to publish this package and use it through npm. So what I want to do here? I'd like to go inside test and do something like npm install frame print. And once this command is done, I should be able to run my test and see the exact same output that's expected. So to get this npm install command to install our own frame print, we need to publish that package now. Since the package name is unique at npm j dot com tow, avoid conflict as we're all doing this exercise, I'm gonna add the prefects to this package here and use my own username at npm JSON com This way, when UI npm install the package, you can use your own username and you can publish your own package as well. So you actually need to create an account at npm JSON Com If you don't have one to publish any package at npm, you need to have credentials. So go ahead and do that. So once you have an account, you can use your user name and password to publish the packages. So here's what you need to do in npm. To accomplish that, I'm going to clear this command will come back to that in just a little bit. And now, from anywhere here in your shell, you need to do npm login. Npm login is going to connect your npm just-as com credentials with your local npm tool here so that you can publish to your account. So, npm Logan, we'll ask you for username and password. Go ahead and put these in and the email as well. This should match the email that you used when you created your account. And now I am logged into npm GS. Very good. Now we can publish the package. So this frame print directory here is not yet a package because it does not have a package that Jason file. So we need to create a package that Jason file Let me see d into IT frame print and to create a package that Jason we-can simply use npm in IT. The package name is no longer frame print, so type in your npm username. Dash frame print. The version can be 100 This is the first release you can add descriptions, entry point, test command, git repository. And I'm going to keep everything default here. Okay, we have a package that, Jason. And guess what? Once you have a package that Jason, all you have to do is npm publish. Just like that, This will publish your npm package to npm j s dot com. So to test that the published process was successful, you need to go to this. You URL npm jess dot com slash package slash the name of the package that you used and you should see your package published. This means that npm can now install this package on any machine. So if you haven't done the first half of this exercise, you can just install this package from npm and just use IT. Now that we have a package published, we can go back to the test directory here, so I no longer need this index suggest file. So focus on this index that Js file under the test directory. Here it is using the name of the package that I just published. But remember that this package is still in npm just dot com itself. We need to bring it here locally, using npm install for this file to access IT. So the command that we need in this case is just npm installed the name of the package and this will download the package and place it under the newly created Node Modules directory right here. As you can see, this is our package. And it is exactly the code that we've written. But now this package was downloaded from npm. And once we have the package downloaded from npm we-can, go ahead and test the script as is, and the script will just work. So this is really how simple it is to publish and use an npm package.

NPX and the NPM Run Scripts

Let's talk about npm Ax and the npm run scripts. Npm Ax is another binary that you get when you install node. It's part of the npm tool set, and the npm Scripts feature is a useful and often underrated feature of npm. IT enables you to automate the way your team uses your-app. You can use npm scripts to start stop, restart or test your-app in a standard way that encapsulates best practices for this exercise. I prepared this four script directory here under the npm folder. In this folder, you should see four files package that Jason and Package Lock that Jason This is so that you can install all the dependencies of this exercise. Ah server that Js file, which creates a simple express web server and the test the Js file, which tests the math square root function. Now you don't really need to test the functions that are available to you in JavaScript like these thes functions are already tested. But this is just an exercise To see examples of how you can use npm scripts, take a look at packaged adjacent. You'll see a scripts section here with three entries, start test and check You can add more scripts in this section if you need to. These scripts are defined with other CLI tools like Node Justin es Linton. These examples To run these scripts, we first need to satisfy the dependencies listed here in the files. UI do that using the npm install command without any arguments just like this. This will create a note modules directory and place all the dependencies we have here under that. So let's test thes scripts one at a time. The start script is going to run this command node server digest. This is the same command that you can just run here to start Server did. Yes. In fact, go ahead and test that it will say server is running and the npm start script is going to do the exact same action. So to run the npm start script, you do npm run start just like that. Now, for some of the special scripts, Start is an example. Test is another example. They actually have shortcuts, so you don't need the run command. You can just do npm start. So go ahead and test that this is equivalent to running note server Duchy s command and it will run the server for you. And you can go ahead and test the Web server on Port 8000 and it should be running. Let's try the other script. Npm run test is going to run the just command. Now, if you try the just command here, it will not work. It will say command not found, although just was a dependency here and the binary for just exist somewhere under the note Modules folder. However, the just CLI tool here is not a global one because we installed IT locally under this folder. The cool thing with npm scripts is you don't need to worry about that as long as just is installed locally under the note modules, the npm script section is going to find it. So if you run npm test another one of the special npm commands that has a shortcut for npm scripts, this will actually fire up jest. IT will find just under the new IT modules, and it will fire it up and run the test. The test that Js file, which is a special name that just is gonna find now if you need to run just right here outside of npm scripts, you have a few options, but the easiest option of all is to use the npm _________. So if you do npm x-excess just MPX is short for npm execute. MPX will also find the just binary under the note modules folder and it will just use IT so npm X just work as well the es lint binary Here in the Czech script is the same story. You can either use it with MPX directly or if you use it through the npm script, it'll work as well. Now, the Czech script here is not a special npm script, So to run it, you need to do npm run check. So this will run the command Eastland Server Digest and it will check the server digest file for any ESL and errors. Now, usually, when you do A s lent, you need an s land configuration. But I think I have a global one. Hears it will just work and it's working and checking that I have console statement and server digest. Now, is lenses really helpful? If this command does not work for you, what you need to do is configure es land and to configure es land. You need access to the s land command itself. Now we don't have it again. This is installed locally under the note modules folder. So to configure is land we can use MPX s lint And what you need here is to initialize eastland with a configuration file so you can use the dash dash in IT argument here and this will ask you a few questions about how you like to configure es lint. For example, I am using a popular style guide so I can use the error functions here to pick use a popular style guide and I am using Airbnb. I like Airbnb because they also support react and I use react. So we'll go ahead and say no to react here just Airbnb and the format can be anything. I like to have it in JavaScript. So what this command is going to do, it will install some other dependencies. As you can see here, those dependencies will have the Airbnb configuration and it will also create an S Linux R C file for your project to work with the excellent. So what's important to learn here is that we use MPX here to access the local binary es land that's included in this project, and we were able to configure es land through that. And if everything works for you, if you run npm run check again, it should use your ears lint and say that console log statement is unexpected. It's a warning. You're not supposed to leave console luck statements around. So the npm Scripts section here is really a good way for a team of developers to have a standard way of running things. This is how we run the server. This is how we test the server. This is how we check the server, and this is really just the basic usage. But there's more to the story. Certain names in the npm run sections are special. You can see the full list of these special commands using npm help npm scripts. Also, let's take a look at that so you'll see them here with prefixes like pre and post. So, for example, you have pre test and post test. These commands will be run by the npm Test Command before and after the command, so let's go ahead and test that I'm going to do a post test. And under this command I'll do something like node dashi to execute as script. And I'll just console dot log in a string here console log, done testing just like that. So guess what Now? When we run the npm test script itself, it will automatically run the post Test npm test, and it will run the just command. And when it's done, it will execute the post test script and output the council log message that we're done testing. So these pre and post versions of the npm run scripts give you an easy way for some flexibility around major npm events, like installing, publishing and testing, and you can use them to customize what's happening around these events. They are very helpful when you need to integrate your project with external servers like a build or continuous integration server, or if you need to do custom actions before or after you release or deploy something new

Updating NPM Packages

in any note project. It's usually a good idea to update your npm dependencies before testing each release to get the updates that have been made to your dependencies. You want to at least get any bug and security fixes in the patch number of these dependencies. It's also much easier to deal with these updates if you do them frequently. The npm update is the command you can use to do that. It respects all the semantic versioning strings that are in packaged adjacent for this exercise. I have this five update directory here under npm and it has a package that Jason file with to exact dependencies, load ash and request. If you notice these version strings for load ash and request do not have any caret-symbol the prefixes. This makes them exact their equivalent to doing equal sign here. Which means I am interested in exactly this version. So the first step is to install these dependencies. So we do that with npm install. This will download the exact versions that we're interested in and place them under the node Modules directory. You can verify what versions were installed using the npm ls command now the npm ls command is going to l s the whole dependency three. So basically all your top level dependencies and all of their dependencies on this request package has some sub dependencies. But if you scroll up a little bit here, you should see the top level dependencies right here at the beginning of the tree. And npm installed the exact versions specified in the package that Jason which means if I issue the npm Update Command, nothing is going to be updated because package that Jason asks for exactly these versions now, by default when you install any npm package, let's, for example, installed the express package. When npm installs that IT rights IT with the carrot IT ation. So this was added to package that Jason. But it was added with the current notation, which means that any update in the minor section off the version is okay, We just got the latest version off express. So npm update will also not do anything. We don't have anything that can be updated. We have the exact versions that we're interested in before playing with the version of strings. Let me remove this express dependency that I just installed you do that with npm Uninstall Express and this will remove it from under the note modules directory. And it will also remove it from package that Jason so we no longer depend on this express package to explore the update process. Let's add a prefix here to the request package. I'm gonna add a carrot to the request package. So this is the default behavior. When you install request on for load ash, I'm gonna add a tilde. So the carrot in request means that any minor update is okay So anything in this section will be updated while the tilde in load ash means Onley patch updates are okay. You can see all the versions that are available in an npm package using the command npm show the name of the package, for example request and this will show everything about request. If you're interested in just the versions, you add the word versions, so npm show request versions, and this will give us an array of all the versions available in request. Now they can't version that we have is here, and the latest version right now is to 87 0 because we've used the carrot in request. The next update process is going to take us from 2852287 Because this is a minor update. And that's okay with the carrot Asian. What about load Ash? Let's check that out. So npm show load ash versions and the latest version for load ash right now is 4 17 10. And what I have here is for 16 to with tell the annotation, which means Onley patch updates are going to be applied. So we're not going to go all the way to 4 17. But we can get 4 16 6 because that's a security and bug level fix. So we'll go from 4 16 2 to 4 16 6 before running the npm Update Command. Anyway, I like to verify what packages are going to be updated and to what exact versions are they going to be updated? And instead of doing this manual ing in your head and checking the versions, there is an npm command called npm outdated. This will tell you what packages will be updated. It will not update the packages, but it will tell you that if you run the npm update these wanted packages are where you're going to get. So the current packages are what you have. The wanted packages are what you're going to get if you run the npm update command and in here, it will also show you the absolute latest packages. If you're interested in those because of semantic versioning in here, we're not really getting the latest package, but rather the latest bug fix that we can have. And again, this is the absolute minimum thing you should do when you're planning to update your packages. However, just be careful and test because sometimes even patch level updates might introduce new bugs in your system. Alright. So to update UI, just run npm update and this will update the packages according to semantic versioning. And once it's done, you can run npm ls I'm gonna pipe that unless and this will give you the latest dependency tree starting from your top level dependencies here that were updated to the latest. According to semantic versioning, the package that Jason file was also updated to reflect the new versions that we're starting with right now. And note how the npm Update command used the carrot notation here. Although I was using the tell the invitation before, so be careful about that. Now, what if I'm interested in a nup date that is beyond the version string? I can do that with npm. Install the name off the package and I can actually place any version here so I can say 4, 17 or just four, and that will give me the latest on the four. Or I could just say latest npm installed load ash at Latest. And this will give me the absolute latest load Ash library, as you can see here for 17. 10. And this match is the latest version for load Ash right here with npm Show load ash version. The singular version here is going to give me the latest version available. Load, ash. And it's the current version that I have in package that Jason. And this happened because I specified that I am interested in the latest version of load ash

Wrap Up

it's a wrap on this npm course module. We covered a lot of topics under npm, but they were really all important and will be needed when working with node projects. I'd like to remind you, though, that npm is just one package manager that you can use. There are a few others, most notably the yawn project by Facebook. The commands for these other package managers might be slightly different, but the concepts are similar. Npm is what you get by default when you install node, but you can easily switch to other managers if you like them better. So in this module we talked about what is npm and why is it needed? UI explored the basic commands for working with npm. UI discussed the purpose of package that Jason and package locked Jason. We learned about semantic versioning and how the npm commands work with them. We learned how to locally and globally install npm packages and how to use these installed packages. In note, we created a simple npm package and published that on npm Js dot com. We learned about using npm X to execute locally installed execute herbal npm commands on. We saw how to use npm run scripts to have a standard way to run and test the tasks in a project. And finally we learned how to check an update your project dependency tree in the next module. We'll talk about the most important aspect about no jazz, which is how it works with slow operations without blocking other operations.

Modules and Concurrency

Defining and Using Node Modules

Let's explore how to define and use modules in note. But before we do that, let me start with the basic question. What exactly is a module in note? The word module is basically a fancy word that means a file or a folder that contains code. That's IT. So this file here with this simple console, the log line is a module. I am currently under the four Modules folder under the one define use folder in the first file, right, there is a module. However, the reason the word module is a bit better to use than using just the terms file or folder here is because node actually does not just execute the file as is. It wraps the file with a function first. This is something that you need to remember. So let me show you what I mean. You know the keyword arguments in JavaScript? If you access that keyword inside the function like what I'm doing in this file here, the cured arguments will represent all the arguments passed into dysfunction, regardless of how many of them get past two IT. So if I execute this file to arguments under this folder, you'll notice How Right here This is the representation off the arguments, keyword. And it's representing all the arguments that we passed here to the dynamic arguments function. So this arguments cured here is a handy way to write functions that except a dynamic number of arguments. Okay, here's a weird question now, and this is one of the questions I'd ask in a note interview. What would know do if you console log the keyword arguments on the top level of a note file like this. If your answer is arguments is not defined here because we are not inside a function, you would not be getting that No job. Your answer is correct in a browser. But no, it has a different story because not internally wraps every file IT executes with a function. This console logline here will actually output something. Let's try IT. Node three. Rapper digests IT outputs exactly five arguments which noted, passed to that hidden wrapping function when it executes your file. You should remember that every time you hear the word module, this is not just a file. It's a function that receives arguments, and it will also return something. Let me write in comments here. What node does internally to this file? There is a function rapper here, So basically, there's the function call, and this function receives a set of arguments and your could becomes the body of this function, and then node will call this function. The arguments that this wrapping function receives are in order exports module require underscore, underscore file name and then underscore underscore dirt name. Have you used any of these arguments before? In your note file, you can use the exports or module the exports to define the A P I off the module. You can use require to require other modules inside this one and the underscore underscore file name has the path of this file and the underscore underscored Their name has the path to the folder hosting this file. All of these objects which she can use inside this file, are not global objects. They are just arguments to the wrapping function. They are customized for each file and they're different in each file. So when inside a file, I do something like exports dot a equal 42. I am just using one of the arguments of the wrapping function. The keyword exports here is not some globally available keyword. It's just the first argument to the hidden wrapping function. This wrapping function is also the reason why in node, when we define a variable in any file on the top level, like, for example, let G equal one. This G variable will not be a global variable at all. It's just a variable inside a function. The scope of this variable is the hidden wrapping function. This is different than what a browser would do if you define a variable top level like this. Browsers do not have this hidden wrapping function. So when you define a variable like this in a browser in a script that variable will be global. IT will be available to all the scripts you include after defining IT, because you're basically putting it on the global scope. But that's the browser, not note. Note has the wrapping function, and this G here is not global at all. It's just a local variable inside the wrapping function. It is really important that you remember that this variable here is just scoped to the built in wrapping function, all right. So besides making five arguments available to you inside any file The wrapping function also internally return something and the thing IT returns here is the module dot exports property. This is what the built in wrapping function return by default all the time. For every file it will return module the exports and module here is just the module argument that gets passed to the function as well. And it's the object that note uses to manage the dependencies and to manage the A _. _ _ of modules Note that you don't need to use the return key word here yourself. No, it will always make this function return. The module exports object, and this is the object we can use to define the A P I of this module. The exports object here is just an alias for module the exports. When node invokes the wrapping function, IT simply passes module exports here as the value of the first argument here. This is why we can use the exports keyword itself to export and new property on the A p I. But what we're really modifying when we do that is the module, the exports object, which is the one being returned. So just like I did exports the A equal 42. Here I can do module the export and let's export another property for this modules. AP I. Let's do be equal 37 I could do that because the module object itself is also an argument that gets passed to the wrapping function. So both A and B are part of the A P I of this module because exports is just an alias to module the exports and were returning module the exports to use this AP that we just defined in these two lines here. There is another file here in the same folder for require, and this is invoking the require function and passing it as a string the path of the module. The result of this require call is really the module the exports object. That node returned from our module. So the module AP I hear becomes the module that exports that the file returned and we can see the console log in here. Let's go ahead and test that real quick note for require. And as you can see here, we're getting the properties of the module that we defined here online. Seven and eight This alias relation between exports and module the exports is the reason why if we reassign the exports object directly. If we do exports equal something, we're not really changing the module. The experts object anymore. We're just reassigning the alias. We're making this variable point to a new local object in here and no longer point to module the exports. So if, for example, you want your top level A p I to-be function instead of an object, which is a valid case that we use all the time. We want our top level a p i to be a function not just an object. You can't do it this way. This is not okay. This will not work again because you're not really modifying module the export. You're just breaking the assignment reference between experts and module the experts. But you could totally do module the exports equal ah function. And that would be okay because module the export is what being returned. And I can change the value of module the exports itself. So this line here is okay. And as you can see, the top level a p I does not have to be an object

Examples of Module APIs

Here are some examples that define and use multiple types of a P I objects. I am now under the two examples folder under the four Modules folder. And in here we have eight files four different AP I experts and how to use them. The first file here is the simple case. When you want your a p i to be a simple object, you don't really need to use module the exports. You could just use exports. So you put exports and then you put properties on your A p I. And to use this module when you call the require function on this module, you get back a simple AP. I object so you can read the elements of the A P i as properties on that object. Note one use duchess. We are getting the values that are exported through the AP here because the FBI is just on object. The second example here the top level a p I is an array. So I needed to use module the experts because I am reassigning the default expert, which is usually an empty object. And now I'm saying my top level a p I is in the rate to use this kind of a p I under to use here DJ s When you require the module, you get back the value that you need that value itself becomes your a p I. And not how you can just in line the require call inside some other function because it's just a function call that returns a value that value is your a p I. And in this case, it's Henry. So note to use the jazz and you get the array directly here from the console log light your-app I can also be just-as string. Look at this file. This a p I is returning at template String. Note that these characters are the back deck characters, not the single code characters because this is a multi line template string and the whole a p I is just returning this string. So if I want to use this a p I when I require the file, I get back an object which is a string. So if I console log this object, it will be a string. So node three used gs. That is the string that this a p I is using, but let's say you do want an HTML template, but you want it to be dynamic. You want to tell your module that you'd like it to generate an HTML template for a certain title. For example, instead of a generic title, How do you do that? You do it by exporting a function. Check this one out. Four. Function here. It's the exact same template text, and it's being done through a template string as well. But the difference is that the top level a p I here is now a function on. I used the shorthand notation for the arrow function here to have a narrow function that receives the title as a single argument and then return a template string that injects the title value right here inside the title tech. To use this, a p I. That is basically a function when you require this function here in four use, right, you get back. Ah, function. I called IT your template generator. It's a function, and you can invoke this function with any argument that you want, because the top level a p I is itself a function. I captured the result of the require call into a variable. And I am now executing that variable because it's just a function. And the result of executing this function is what the function returned here, which is the template. So this becomes my template and I can console log that so note for you. Study s and you get the exact same template. But now it is being customized with a custom title that I get to pass to the function that this a p a is exploring. So this a p I is now a lot more flexible than the previous one, which just hard coded a value for me. So these are just a few examples of how flexible this module the exports object is and how you can use it to return any kind of a p I in a node module.

Node's Global Object

if defining a variable on the top level scope in a note module does not make a global one. Is there a way to define a global value in node? The answer is yes, but you should really avoid doing that. The Onley Global variables in note, are the variables attached to this special global object. This global object is the equivalent to the window object in browsers, and it's the only global concept in note. If you inspect this global object, I'm using a dirty trick here to Onley. Show the top level properties on this object rather than inspecting it as a tree because it's a big one. If you execute this file. No, the one there that yes, you'll see a few things here on the global object. There is the process object, for example, and there are other features like buffers and timers. All of the's here are globally available in all node modules because they're attached to this special global object. So when you use as a time out call set time out, you're actually using global dot set time out. But because it's part of the global object, we can use it directly. We don't need to do global dot because that's the concept of the global object. In note, things will just be available globally. You can also attach new things to this global object yourself in the to set the Jets file here I have a simple example. I am doing global The answer Equal 42 making answer a new global value Now that you can access in any node module, here's how he contest that in the two tests suggest file here I am requiring the file that added the global value and then console logging. Answer directly, not as part of a napi I. And guess what? If we execute to test here because answer was set on the global object, you can access it from anywhere directly. Pretty cool, right? Wrong. Don't do that. Global values like this are bad. This is true here, and it's also true in the browser environment. You should not make your code depend on any global state. Just treat this global object as a built in thing that node itself uses, and you shouldn't do not attach anything to IT.

The Event Loop

Let's work under Folder four. Event loop Here. The first file here. One logged a jazz has a single console. The log line. Execute this simple file note. One logged the jest line. What I want you to notice now is that note has started an operating system process here, and it's now done with that operating system process. No, IT has finished the process, and the operating system terminated that process. A note processed by default will not keep running in the background unless it has a reason to. This one liner script here did not really give the note process a reason to continue running. Let's now give the note process a reason to continue running. We-can do so by starting an interval timer. We've learned about timers in a previous module. Under this file to Interval. There is a simple interval call here that executes a console logline every five seconds. Go ahead and execute this file now node to interval and not how the note process now did not exit. IT is running and it will continue running forever until it gets crashed by an unexpected error or the user killed it manually with control. C the real reason that process did not exit is that notes. Event loop is itself busy now. What is this event loop thing you ask? It is your best friend and node. It's the hidden magic that will take care off anything asynchronous for you. And you don't have to worry about working with threads in other languages. If you need to do a sync rinse work, you have to manage. Threat yourself. You have to start them. Do the a sync work inside of them, monitor them, make sure they don't access shared data or if they do, you want to make sure that there are no race conditions. It is a complicated task now. Some languages make it easier than others, but I think the big winner in this domain is note. Because you just use notes. A P I and Mr Event Loop here will do all the heavy lifting. The event Lube is just a simple, infinite loop that's built inside node, and its main task is to monitor any asynchronous operations that need to be run and figure out when they're ready to be consumed. In this example, the event Lubell Monitor that set interval timer and every five seconds will take the intervals callback, which is the first argument to set Interval the arrow function here. And it will send this error function to V eight, and V eight will execute what's inside that function. Because this is in every five second kind of thing. The note process is going to continue to run forever, and it will not exit. So while this note processes running, if you go to in another terminal and try the command PS dash E F to list all the running processes and pipe the output of this command on grip note to just filter the list. Thio any processes that are matching the word node. This is a Linux command. But the same list of processes can be seen and filtered with the graphical program that monitors process activities in your operating system. So you should see the process hosting our script right here. You see that it is still running. Now I have a few other processes that are matching node. I think these are actually the Adam editor itself here. Believe it or not, this Adam editor here is a note application. It is a complicated one. But it's simply run with node, using an application called Electron, which allows you to use web and no technologies to build cross platform desktop applications for Mac Windows and Lennox. How cool is that? Okay, so our process here is the last one here because we started it last, so it will have the highest process I'd. You can kill our continuously running note process, using the Linux skill Command itself on giving it the process I d here. But you can also kill any active note process using Control C on its output here. And that action will stop the event loop and then remove the process from the operating system. Run the same PS dash e f Grab Note command now, and you'll see that the process that was hosting the interval file is gone. Notes. Event Loop works with multiple phases and queues. At this point, what I want you to remember is that every note process starts this infinite loop that we call event loop. But when the process has no asynchronous operations to perform, the event loop will exit and the operating system will terminate that note process

Errors vs. Exceptions

What is the difference between errors and exceptions and error is simply a problem. Unknown problem applications are usually not prepared to deal with it, while an exception is a condition that applications know about and are prepared to deal with it. They catch that condition and do something with it. Let's talk about that in note. In The Five Errors Directory here, I have three files. The first file is one loop, and this file is simply looping over an array of the files, which uses files from the same directory. I'm looping over this Falls array using a four each call. And for each file, we are basically reading the content of the file using the read file sync method, which is the first time we're seeing this method. It's equivalent to read file, but it will do the reading synchronously, not a synchronously. We're going to talk a little bit more about that in the future, of course module. But for now, let's focus on thinking about what's gonna happen when this code encounters a problem. So let's quickly run this code and make sure it doesn't have any problems. Right now it is running, and it's reading to files data. Very good. Now, what if I injected? Ah, file path here. That does not exist. So this file now in the middle does not exist in the current directory. What do you think that good is going to do? The code is going to try and read a file that does not exist and note will _____ and exit. So after reading the first file successfully for the second file note crashed on we're not reading the third file in here. And this is normal when note executes an error like this one, which is basically not planned for it will just _____. And this is important to remember here because although this process started the infinite event lube to do any a sync actions, IT immediately stop that lube when it encountered this unexpected. There, I say unexpected error here because the code did not account for the possibility of that error. We can make this code account for the error by simply making an exception for IT. UI right code to represent that exception. So let's assume that trying to read a file that does not exist is not really a problem for this code. We're gonna upgrade this case from a problem which is an error into a condition which is an exception. And the easiest way to do that is through a try catch statement. So if you look at the second example file under this folder here to try this good is using the same invalid file and the same code. Except now I've put the file reading part inside a dry catch statement. So try this code and catch any errors. And inside this catch block we-can, do whatever we want with this error object. Once you catch the error like this, the note process will not _____ an exit when it encounters any error within the catch block when we run this code, because it's going to generate an error. But that error is wrapped inside a try catch statement. The catch block will be executed. So not how the note process did not _____. We just got the file not found message for the second file. And then the note process continued to read third file because now an invalid file path is no longer a problem here. It's just an exception in this code. It is okay to encounter files that do not exist and just continue with code. So this is a great feature, but it's also a dangerous one. This code means that we're okay with non existing files when we attempt to read them. But it also means that we're OK with any errors that happened when we read a file. Not just the error about a file that's not there. If, for example, the file is there but has corrupt data, this good will treat the other error exactly the same. Making this council logline here Not really inaccurate one. Let me simulate that. The second argument for read file sync here except an encoding string So you can pass an utf eight here to say I'd like to encode the content of this file when I read it with utf eight, let's pass an invalid, including label. If you execute, that could now because we did try, catch and generically saying file not found. When you encounter an error, we're going to see the file not found message for all of them. But really the error that happened was not file not found. The error that's happening here is that the second argument to read File sync is an invalid, including label, so this console log message is not accurate. Amore Accurate message here would be something went wrong, and we're going to completely ignore it because this is just a generic catching of the error and that's not good. Here's the thing. If you want your code to Onley, catch the case for non existing files. You should make this catch block here a bit more specific in the third example file here. You're going to see an example of that. Take a look at three. Throw that jazz and you'll notice the exact same code. Except we're not generically catching the error message. We have an if statement on this. If statement is basically saying Onley, ignore the error. If it's a file not found error. Otherwise, throw the error object again, and this throw line is what note would have done with the error if we did not have a try catch statement making this code only ignore a specific case and perform the default behavior. Otherwise, in note, the default behavior oven error is to have the process exit because the state of that process is unknown and it is not safe to continue running with an unknown state. So let's try this one node three. Throw that us. This is fine here because this is an actual file, not found error. And now let's simulate a bad, including string again. Run the process and the process will _____ and exit because this is a problem. It's an unknown error, unknown state of the process, and the safest thing to do for that case is to have the process _____ and exit.

Node Clusters

okay, You might be wondering now if it's a normal thing for a note process to _____ and exit, and we should definitely let it do so. How is this going to be an acceptable thing in production? Remember when we talked about why nodes is named node? Because you don't run a single note process in production, you run many. One working process exiting should not mean the system is down. You should be running a cluster of note processes, and that cluster will have a master process, which should be monitoring your application worker processes. This is true. Even if you're running a node application on a single server, it's often the case where production servers will have many CBU course. You should be running annoyed. Process for each core if you're not running cluster. In that case, you're not really utilizing the full power of your machine. And even if you're single, production server has a single core. You should be running a cluster anyway, because that cluster has the simple job of monitoring the actual note process and starting a new one. When the process crashes and exits, you can run a simple cluster in node using the built in cluster module on, I go in depth about that topic in the advanced Node.js course here at Pluralsight. Alternatively, you can use one of the many tools that wrap the cluster module to run your note application in production. PM two is one example of these tools. If you run your note application through a tool like PM to that tool, can automatically use all the available course in your server, and it will automatically create a new process every time an active process crashes and exits. PM two can also reload your application without any downtime. A tool like PM to is really a must and production.

Node’s Asynchronous Patterns

note originally used the callback pattern for everything asynchronous today. Notice changing, and it's incrementally adopting other patterns as they surface in the JavaScript language itself. Let me show you some examples of that under the A sync patterns. Here there are six files. Let's start with one sync. This is the pattern usually used in other programming environments. Slow actions are usually handled with threads directly, and the code does not have any patterns to consume. Data coming from these slow actions. You can do that as well. In load. We've seen this read File sync method in previous videos. It's the synchronous version that note makes available to read files. You don't need any pattern to consume its data. You get the data when you call that method, and the whole program here does not go through the event loop were directly using the operating system synchronous file reading a P I. When you execute this code, you'll see the file data console logline before the test console logline because it's all synchronous Now. Look at the to call back pattern file here. This one is using the read file method from the built NFS module. This method is asynchronous. It needs to go through the event loop. We can't access the data directly after calling this method. This is why Note came up with this callback pattern, where the last argument of any asynchronous function like read file here is itself a function which is known as the callback function. This callback function is always the last argument of the host function. The event loop will make this call back executed when the operating system is ready with data for us. As I explained in the first module of this course, one thing I want you to notice about this callback pattern is how the callback function always receives an error object as it's first argument. The data comes after that in the second argument, and sometimes in many arguments after that. This first error argument is standard in the note idiomatic callback pattern, which is why that pattern is often referred to as the error first callback pattern. If there is an error in the code, this error first argument will be an error object, and if there is no error in the code, this first argument will be passed as null when we execute this file. You'll see the test line first and then the file data line here because of how read file is a sync. Basically, this code was executed in two IT orations of event Loop. The first iteration executed read file itself and the console log test lines. And that first iteration, Onley, defined the callback function. And also in that same IT oration note will ask the operating system for data later on once the operating system is ready with data. And this could be a few seconds later, the event Liu will go through another iteration where it will now invoke the callback function and execute the console. Log online. Four. Here This callback pattern is good but limited, and it introduces some complexities and inconveniences. One famous inconvenience about call backs is the fact that we need to nest them inside each other if we're to make a synchronous actions that depend on each other. Here's an example under three callback nesting that yes, we start with the same read file method here to read the data of a file, and then, once we have that data, will use another FS method here, right file to create a copy of this file. Note how I needed to nest, the callback of the second operation within the callback of the first operation. And if I have yet another a sync operation to be done after the right file, I'll have to do more nesting her