Import npm Modules: Node.js Development

A free video tutorial from Andrew Mead
A Full-stack Developer & Teacher
Rating: 4.6 out of 1Instructor rating
4 courses
396,736 students
Importing npm Modules

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 Node.js. In this video, you're going to 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 9 p.m. JST, 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're 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 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 website that we want to install. So right here, we're going to 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 and 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 going to hit enter. We have version, we have description, entry point, test, command, git, repository, key words, 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 in it 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 will explore as we use Jason throughout the class. It's something we're going to 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 going to 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 JS 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 lowercase 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, 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 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 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 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, 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 going to 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 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 website they used npm i validator. Those are identical. I is just a shorthand for install. You are 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 .8.0. In this course, I'm always going to specify package or 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 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 locked 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 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 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 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 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 loaded 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 required statement to this file right here. We're going to 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 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 like to point you towards the documentation, since that's going to 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 100 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.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 going to call the function right inside of console. 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 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 CLS on windows. Then I'm going to run Node with Apks. 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 going to remove Andrew and the app sign leaving just example dot 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 as 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 going to scroll down to IS and we're looking for you for is your URL 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 going to remove is email something we'll be using later in the class. I'm going to swap it out with is URL, then I'm going to change the string value I provide. Let's go ahead and try my own site url https colon forward slash forward slash midi i. Oh, I'm going to save the file. I'm going to rerun the program and this time we get true. Now I'm going to 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 S6 and S6. This is a node course that uses. Six is seven 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 there using a slightly different syntax using the input 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 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 a 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.