Import npm Modules: Node.js Development

Andrew Mead
A free video tutorial from Andrew Mead
A Full-stack Developer & Teacher
4.7 instructor rating • 4 courses • 328,789 students

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:13 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 [Auto] 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 Doc J s 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 NPM J S dot 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 six point four point one. Now the specific version of NPM you're using does not matter as long as you're using version 5 or greater. So as long as that first number is either 5 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 in it. This command is going to initialize NPM in our project and in the end of the day it's not going to 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 Web site that we want to install. So right here we're gonna go ahead and run NPM in it. 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 by just hitting enter or we could type something custom to override that value for every single question it asks. We're going to stick with the default value so we have package name. I'm just gonna hit enter. We have a version we have description entry point test command get 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 get 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 OK now what exactly is it doing well it tells us it's about to write a package dot Jason File to the notes app directory down below. If 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 in it to actually create that file and now we have a brand new file in our project route. If I crack it open we can see that has NPM promised. It looks exactly like what we had output it in the terminal down below. The extension for this file is Jason which stands for a 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 Jason 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 Jason. 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 going to list out all of the NPM packages we want to use to start let's go ahead and move to NPM J and find a package we actually want to 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 going to 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 lower case validator. Now when we click that it's going to 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 they get hub home page and the weekly downloads. This is a very popular package with over one million weekly downloads. So if you wanted to perform a little validation in your note 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 going to want to write test cases for it to make sure there are no edge cases. And in general you're going to have to keep up with that code as node progresses over time. Now that's option 1. 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 going to 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 going to write code. We are but for some things we're going to 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. You are L's 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 it to install it right here lowercase the validator is the package name that we need and we're going to head over to the terminal and install this. Now we want to 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 Web site 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 going to specify the specific version we want to install. So at then the version number I'm going to be using the latest version currently available which is ten point eight point zero in this course I'm always going to specify package versions to make sure that we're always on the same page NPM modules do change their API over time so to ensure the video's always work I'll be lacking us into specific packages including updates when API is change. So right here this is the command we want to run. Now when we run this what's it going to do. Well it's going to go off to the NPM servers. It's going to grab all of the code for that package. And it's actually going to add it into our application and we'll notice that when we ran that command two things happened one we got a package hyphen LOC dot Jason File and two we got a new directorate 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 of validator and actually change these files and we'll talk more about that as we progressed through the course and learn more about package management when it comes to working with node modules. It's just going to 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 hyphen locked. Jason 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 char 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. Jason 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 dot J. S 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 going to add a second requires statement to this file right here. We're gonna go ahead and use require like we did previously and we are indeed going to 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 going to end up looking at the documentation for every tool we install. I'd 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 is email this allows us to determine if a given email is valid and that's something we are indeed going to 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 dot log called down below so we can print some output to the terminal and instead of creating a variable and then passing that into council dot log I'm just gonna call the function right inside of console dot luck. So right here validator dot the method name that's is email 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 at example dot com which it 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 going to clear the output using the clear command or CLSA on Windows. Then I'm going to run node with app dot J s when I do that. What do I get. I get my first piece of information from line 5 then I get true which is coming from line 7. 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 dot com I'll save app dot J.S. again I'll rerun our script and this time we correctly get false the information passed in is no longer a valid email so is email 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. 4 is you are all right here we have another method allowing us to determine if a given string is U.R.L.. So let's go ahead and test that out. I'm going to remove is email something we'll be using later in the class. I'm gonna swap it out with is you are L.. Then I'm gonna change the string value I provide. Let's go ahead and try my own site. You are l h t t P.S. colon forward slash forward slash meat dot I oh 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 you are out 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 iOS 6 and iOS 6. This is a note of course uses iOS 6 iOS 7 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 j us when we want to 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 going to 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 going to 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.