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
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
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.
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.
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.
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 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.
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.
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.
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.
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
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.
in this module. We're going to talk about two of the core fundamentals of note. It's module system and how to define and require modules using the exports and require objects. And we'll also talk about how no, IT handles slow operations and allow the execution of many things at once without using any threads, which is a big deal. Let's start with the simple module system and talk about the three important keywords here. The module keyword, the exports, keyword and the require keyword.
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.
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.
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
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.
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.