Import npm Modules: Node.js Development

Lecture description
When you install Node.js, you also get npm. npm is a package manager that allows you to install and use third-party npm libraries in your code. This opens up a world of possibilities, as there are npm packages for everything from email sending to file uploading. In this lesson, you’ll learn how to integrate npm into your Node.js app.
Learn more from the full course
The Complete Node.js Developer Course (3rd Edition)
Learn Node.js by building real-world applications with Node JS, Express, MongoDB, Jest, and more!
35:03:06 of on-demand video • Updated March 2021
Completely refilmed for 3rd edition
Build, test, and launch Node apps
Create Express web servers and APIs
Store data with Mongoose and MongoDB
Use cutting-edge ES6/ES7 JavaScript
Deploy your Node apps to production
Create real-time web apps with SocketIO
English [CC]
Andrew: You now know how to use the node module system to load in core node modules like the file system module and other files you've created like notes.js. In this video, you're gonna learn how to use the module system to load in NPM packages. This is going to allow us to take advantage of all of those awesome NPM modules from right inside of our Node applications. There are an endless amount of awesome useful NPM packages that we can install so we don't have to recreate the wheel from scratch. There are things that pretty much every application out there needs to do. Examples would be validating data like emails and maybe even sending an email. These are core functionality, not specific to what your application does for your users. So if we use NPM modules to solve common problems which is indeed the standard in the Node community then we can spend our developer time focusing on the awesome features that make our app unique. So as I mentioned a bit earlier in the class when we installed Node, we also got the NPM program installed on our machine. This gives us access to everything over at npmjs.com which we'll head back over to in just a few moments. Now, before we can actually use any of these modules in our script we have to take two very important steps. One, we have to initialize NPM in our project. Then two, we have to install all of the modules we actually want to use. So let's go ahead and see how that happens. First up, let's initialize NPM in our project which means we have to run a single command from the project root. That root directory is the notes app folder so make sure you're running commands from there. In the terminal down below I am indeed accessing that directory. Now, when we first installed Node we got the version of Node we were using by using the node command with the V flag. When we installed Node, we also got access to the NPM command line tools. We can run that with the v flag to get the version of NPM we're running. And right here you can see I'm running version 6.4.1. Now the specific version of NPM you are using does not matter as long as you're using version five or greater. So as long as that first number is either five or higher which it should be, you're good to go. Now from here we have to initialize NPM in our project and we do that by running a single command from the root of the project npm init. This command is going to initialize NPM in our project and in the end of the day it's not gonna do anything fancy. It is simply going to create a single configuration file that we can use to manage all of the dependencies from the NPM website that we wanna install. So right here, we're gonna go ahead and run npm init. Now it has a lot of information telling us exactly what's happening. In the end of the day, what's really going on is that NPM is asking us for some information to populate various fields in this configuration file. Now we can type out custom answers. So for example, the first piece of information it wants is just a name for our package. So some sort of name for this project. Now by default it uses the folder name notes app. We can choose to use that budget hitting Enter or we could type something custom to override that value. For every single question it asks we're gonna stick with the default value. So we have package name. I'm just gonna hit Enter. We have version, we have description, entry point, test command, git repository, keywords, author and license. Now there are a few of these fields we'll be exploring in detail later. We'll talk about testing when we explore testing and we'll talk about the git repository when we set up deployment. Many of these fields, however are for folks who are creating NPM packages which is not what we're doing. We're creating a application on our own and we're trying to consume NPM packages. So the values for many of these are not important for our purposes. Right here we can hit enter on that last one and it's asking us if things are okay. Now what exactly is it doing? Well, it tells us it's about to write a package.json file to the notes app directory. Down below is this is the exact contents it's about to write to that file. Everything looks good. We can type yes to confirm that we want npm init to actually create that file and now we have a brand new file in our project root. If I crack it open, we can see that as NPM promised it looks exactly like what we had outputted in the terminal down below. The extension for this file is json, which stands for JavaScript Object Notation. And as you can see, it looks a bit like a JavaScript object. There are a couple subtle differences we'll explore as we use json throughout the class. It's something we're gonna be covering in great detail. For now, all you really need to know is that you have to use double quotes instead of single quotes and all of your property names like name or author, they also need to be wrapped in quotes like we're seeing here. If I were to remove the quotes from one of our property names like license, this would be valid in JavaScript but we can see it's invalid in json. So let's go ahead and bring those back. Now this file is gonna be used to manage all of the dependencies that our application needs to run. So in here we're gonna list out all of the NPM packages we want to use. To start, let's go ahead and move to npmjs.com and find a package we actually wanna work with. Now for this example, we're going to install the very popular validator package which gives us all sorts of awesome tools to perform data validation. So right here in the NPM search bar I'm gonna search for validator and we're looking for that first result, the validator package. Now there are other validation packages out there. There's even one with a capital V. We want this first result, lowercase validator. Now when we click that it's gonna bring us over to the NPM package page. This is a great page. Every NPM package has one and it gives us a ton of information about the package. We have the documentation for how to actually use it and on the right hand side we have a bunch of great stats about the package. Things like the version number, the GitHub homepage and the weekly downloads. This is a very popular package with over 1 million weekly downloads. So if you wanted to perform a little validation in your Node app there are two ways you could go about that. The first approach would be to write all of the validation code yourself. You have to write the code, you have to maintain it, you're gonna wanna write test cases for it to make sure there are no edge cases, and in general you're gonna have to keep up with that code as Node progresses over time. Now that's option one. Now, when you're creating an application I doubt that validation is what makes it unique. So if I'm creating a weight loss application as an example I likely have some sort of reason why I'm doing it. I have a model about either diet or exercise or habits that's gonna help people lose weight in a way they weren't able to before. What makes my app unique is likely not how it validates emails. So sure you could write that code but it's a much better practice for a lot of these basic features to take advantage of a well-tested NPM package like this one where millions of different applications and utilities are taking advantage of it all the time. Now, that's not to say we're not gonna write code, we are but for some things we're gonna take advantage of other packages that allow us to get it done in a much more secure way. So in this case, the validator package has all sorts of tools for validating emails, URLs, phone numbers, social security numbers, credit cards and other types of string information like that. Let's go ahead and install it and see how it works. Now what we're gonna do is note the package name because that is essential. You can actually see a command over here that we can run to install it right here. Lowercase V validator is the package name that we need and we're gonna head over to the terminal and install this. Now we wanna run the command we're about to run once again from the notes app directory right here that's NPM install validator. Now you'll notice on the website they used npm i validator. Those are identical, I is just a shorthand for install. You're more than welcome to use either approach. Now from here we're gonna specify the specific version we wanna install. So @ then the version number. I'm gonna be using the latest version currently available which is 10.8.0. In this course I'm always gonna specify package versions to make sure that we're always on the same page. NPM modules do change their APIs over time. So to ensure the videos always work, I'll be locking us into specific packages, including updates when APIs change. So right here, this is the command we wanna run. Now when we run this, what's it gonna do? Well, it's gonna go off to the NPM servers. It's going to grab all of the code for that package and it's actually gonna add it into our application. And we'll notice that when we ran that command, two things happened. One, we got a package-lock.json file, and two we got a new directory, a Node modules directory. Let's take a quick look at both. First up Node modules, this is a folder which contains all of the code for the dependencies we installed. So if I crack this open, what do we have? We have a single directory validator. That's the package we installed, and if we open that up it's all of the code for the validator package. Now the Node modules directory is something we should not be manually editing. We should not go inside a validator and actually change these files and we'll talk more about that as we progress through the course and learn more about package management. When it comes to working with node modules it's just gonna get generated and edited when we run NPM install commands. So we use NPM install and NPM maintains this directory. The same thing is true with package-lock.json. This is a file which contains extra information making NPM a bit faster and a bit more secure. It lists out exact versions of all of our dependencies as well as where they were fetched from and we also have a SHA hash making sure that we're getting the exact code that we got previously if we were to install a dependency again. Once again, this is not a file we should ever be editing. Once again, this will be maintained by NPM. So we have our package installed and when we ran that command it was even added to package.json. We have a dependencies property, we have our dependency name along with the version we installed. Now that we have it installed, we can move into our Node app, a file such as app.js and actually load it in with require and take advantage of some of the functionality it provides. To load in an NPM package we once again use require. I'm gonna add a second require statement to this file right here. We're gonna go ahead and use require like we did previously and we are indeed gonna pass in a string. Now, for those core Node modules we typed out the module name. For our files we would start with dot forward slash to provide the relative path to the file. For NPM modules, we list out the NPM package name. So in this case, that would be validator and this is similar to what we do with those core Node modules. Now require is going to return all of the stuff that the validator package provides us. So right here I can create a variable like validator that's going to store the contents that comes back from require. Now, when it comes to figuring out how to use a given package, this is when you just have to turn to the documentation to figure out how it was intended to be used. We're gonna end up looking at the documentation for every tool we install. I like to point you towards the documentation since that's gonna give you all of the information you would need to learn more about how something works or to explore other ways a given tool can be used. Now for our purposes on the NPM package page, we have all of the different ways that this tool can be used. If we scroll down to the validators section we have a method and we have a description of how it works. There are maybe a hundred different methods for all sorts of different things we can do. One of the methods is isEmail. This allows us to determine if a given email is valid and that's something we are indeed gonna take advantage of. This method can be accessed directly on validator which is an object. So let's go ahead and test this out. I'm going to add a console.log call down below so we can print some output to the terminal and instead of creating a variable and then passing that into console.log, I'm just gonna call the function right inside of console.log. So right here, validator dot the method name, that's isEmail, and we're going to pass in to that method call a single string argument. So right here, let's go ahead and try something like andrew@example.com which should indeed be a valid email as it contains all of the component pieces. Now let's run our application. From the terminal down below I'm gonna clear the output using the clear command or CLS on Windows. Then I'm going to run Node with app.js. When I do that, what do I get? I get my first piece of information from line five. Then I get true, which is coming from line seven. So here we have a valid email. Now let's switch that up. I'm gonna remove Andrew and the at sign leaving just example.com. I'll save app.js again, I'll rerun our script and this time we correctly get false. The information passed in is no longer a valid email. So isEmail returns true if the string is an email, it returns false if the string is not and there we go. We were able to install an NPM package load it into our Node application and take advantage of it to do something meaningful. Before we wrap this one up let's go ahead and explore one more method. Right here we have an alphabetical list of methods. I'm gonna scroll down to is and we're looking for you for isURL. Right here we have another method allowing us to determine if a given string is a URL. So let's go ahead and test that out. I'm gonna remove isEmail something we'll be using later in the class. I'm gonna swap it out with is isURL. Then I'm gonna change the string value I provide. Let's go ahead and try my own site URL https://mead.io. I'm gonna save the file. I'm gonna rerun the program and this time we get true. Now I'm gonna mess that up. Maybe I'll do something like remove one of the colons and the forward slash, I'll run the script again and what do I get? I get false. This is indeed an invalid URL. Now, when it comes to taking advantage of the documentation for a given package, it's usually best to find an example. Sometimes the documentation itself doesn't really make it clear how something is to be used. Up at the top though we can see there are real examples similar to what we just did inside of our own project. Now you'll notice there are two versions here No ES6 and ES6. This is a Node course that uses ES6, ES7 and more modern features throughout. The only big difference here is that up above we're using require which is what we're using in Node and down below they're using a slightly different syntax using the import keyword. Node currently does not support the import keyword. Support is coming for it later down the line and when it is supported I'll add a section covering it. But for now in Node js, when we wanna load something in reuse require. So right here this would be a great example to kind of help us figure out exactly how the package is intended to be used. That's where we're gonna stop for this one. We have installed the package, we've required it into our file, and we've used it in the next video. As a challenge, you're gonna end up doing the same thing for a different library. I'm excited to get to that. So let's go ahead and jump right in to the next one.