Intro to Node Requiring and Using Node Packages
Learning Objective: By the end of this lesson, students will be able to require and use methods from an installed Node package.
Using a Node package
We’re going to make use of the validator package, so install it with:
npm i validator
Let’s explore how to require and use its validation methods in our project.
Requiring and using validator
-
Review package docs: Before using a package, it’s important to consult its documentation. Review the validator documentation on npm for detailed information and usage examples.
-
Require validator: At the top of
server.js, bring the package into this file using CommonJSrequire()syntax:const validator = require('validator');Using
constensures that thevalidatorvariable won’t be reassigned accidentally.📚 The require function loads the specified module. If a file path is given for a module (such as
require('./myModule')), it directly loads the file. If a package name is provided (such asrequire('validator')), Node looks for the module in thenode_modulesdirectory. -
Test a method: Select a method from the
validatordocs - let’s useisEmail(). We know from the docs that this method will returntrueorfalsedepending on whether or not the value passed into this function is formatted as an email address.Let’s try it:
console.log(validator.isEmail('test@example.com')); // Expected: true console.log(validator.isEmail('not-an-email')); // Expected: falseThis will log whether these provided strings are formatted as email addresses.
-
Run your code: Run the test file in the terminal.
node server.jsCheck your terminal output to see the results!
🎓 You Do
Validate the casing of a string! Using the validator docs as your guide, try out the isUppercase() method.
Test if 'HI THERE' is uppercase, and log the result.
🧠 Some large packages even have their own website with documentation. Usually, these packages will have a link to their website on their npm registry page or any GitHub documentation they may have.