paint-brush
A Beginner’s Guide to NPM Packagesby@katia.gilligan88
4,077 reads
4,077 reads

A Beginner’s Guide to NPM Packages

by Katia GilliganSeptember 13th, 2018
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Node.js is a Javascript runtime that can be run outside of the browser on a V8 Engine. The V8 Engine is built in C++. Its job is to convert Javascript code into machine code, giving it the same capabilities as some backend scripting languages, such as Python. Node is single threaded and non-blocking. What does this mean? Well consider this example:

Company Mentioned

Mention Thumbnail

Coin Mentioned

Mention Thumbnail
featured image - A Beginner’s Guide to NPM Packages
Katia Gilligan HackerNoon profile picture

What is Node.js? What is npm?

Node.js is a Javascript runtime that can be run outside of the browser on a V8 Engine. The V8 Engine is built in C++. Its job is to convert Javascript code into machine code, giving it the same capabilities as some backend scripting languages, such as Python. Node is single threaded and non-blocking. What does this mean? Well consider this example:

You need to access a user’s information from a database. You send a request to access the data and it is shortly followed by a response a couple seconds later. So, what if you want to access multiple users’ information? First, you send a request for one user’s information, then you get a response. The second request waits for the first user’s response, and only then sends a request. This process is called blocking or synchronous. Blocking code takes longer to execute. Non-blocking code runs asynchronously, allowing for multiple requests to be sent one after another, before a response comes back to the user.

Therefore, as Node.js documentation states:

“non-blocking I/O model makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices”.

Node.js is also very popular due to its large ecosystem of libraries known as NPM modules. NPM stands for Node Package Manager. It is the largest software package library in the world, with over 600,000 packages. The Node.js installation comes with a Command Line Interface (CLI) for npm which allows for developers to interact with packages locally on their machines.

The NPM library contains many great tools for development, that can abstract away complexity and help reduce the size of your codebase. However, the library is also very large, which can add difficulty in finding the right modules and tools for your next application. Therefore, I wanted to shed some light on a couple reputable modules that I have found very useful in development. For this article I only chose 9 modules to discuss, but please be aware that the list of useful modules goes on and on. In fact, I would love to hear your feedback in the comments section about some of your favorite and most useful packages! Now lets get to it!

I will briefly introduce each package, its benefits, and give a short example, so feel free to follow along in your code editor!

1. Express

Express is a web application framework that wraps a Node.js web server. It offers a simple API, middleware, and routing. Currently, it has over 5 million weekly downloads. Express can be used for building RESTful APIs, serving single page applications, and it can also serve static content(HTML, images, etc). It is very simple, unopinionated, and lightweight. Getting started with using it is also very easy.

First, cd into your project directory on the command line and then add:

npm install express

Then once the module is downloaded, inside the root folder of your project create an index.js file. In this file, add the following code:

const express = require('express');


const server = express();server.use(express.json());



server.listen(5000, () => {console.log("Server running at port 5000")});

Now finally, in the command line, in your project directory add:

node index.js

And there you have it! You just created an express server that is connected to http://localhost:5000. Now lets create a simple HTTP get request in Express that sends back a simple “Hello World” message. Right above server.listen add:



server.get("/", (req, res) => {res.send("Hello World!");});

Now in your browser type in http://localhost:5000 into the URL, and voila! You should see “Hello World!” printed to the screen.

For further examples and documentation of Express, visit https://expressjs.com/en/api.html

2. Nodemon

Nodemon is a useful CLI utility that can be used in the development stage of an application. Every time changes are made in an application, the server needs to be manually restarted. This process can quickly get very tiring and tedious. Nodemon alleviates this process, by wrapping the Node application, watching for file changes, and then automatically restarting the server every time a change is made.

Start by installing npm as a development dependency in the project directory.

npm install nodemon --save-dev

Then, in the command prompt, restart the server, this time using nodemon:

nodemon index.js

You should see the following script after restarting the server:




[nodemon] 1.18.3[nodemon] to restart at any time, enter `rs`[nodemon] watching: *.*[nodemon] starting `node index.js`

3. Colors.js

This package is very popular with over 7 million weekly downloads and is a dependent in almost 12,000 packages. Colors.js adds color and style to the Node.js console. It provides a variety of text colors, background colors, some styles such as italic and bold, and some crazy fun options such as rainbow, trap, and america.

First, install colors.js:

npm install colors

Then add the following code into your index.js file:

const colors = require('colors');




console.log('Hello World'.cyan);console.log('So cool!'.underline);console.log('Rainbow colors!'.rainbow);console.log('What is this do?'.trap);

Its as easy as that! Explore more colors and styles at https://www.npmjs.com/package/colors. Go spend a minute playing around with all the different options!

4. Lodash

Lodash is a very popular Javascript helper library for strings, arrays, and objects. It provides utility functions that simplify the manipulation of objects and arrays. It was inspired by Underscore and its main goal is simplicity, modularity, and performance. Some new ES6 features can now be used instead of lodash, such as map, reduce, and filter. However, lodash still remains very popular with about 14 million weekly npm downloads. Let’s explore a couple utility functions:

First install lodash into your project directory:

npm install lodash

Then import lodash into your index.js file. It is common practice to define the variable with an underscore.

const _ = require('lodash')

Now let’s explore the function _.uniq(). The uniq function will take an array as an argument and return all unique values. It will get rid of all duplicate values.


const numbers = [1, 1, 2, 3, 4, 4, 5, 5, 5, 6, 7, 8, 9]numbers = _.uniq(numbers);

//OUTPUT: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Let’s look at another helper function: _.intersection

Intersection takes two arrays as parameters, and returns all common values that are found in both arrays.


const numArr1 = [1, 55, 6, 78, 92, 102, 45];const numArr2 = [2, 6, 45, 22, 55, 130, 46];

const commonNumbers = _.intersection(numArr1, numArr2);

//OUTPUT: [55, 6, 45]

There are many more different methods so go check them out in the documentation: https://lodash.com/docs/

5. Joi

Whenever a user sends data in a request, it is important to validate the input. Why? Because you should never trust the user input. Validating input can stop incorrect formats, too much unnecessary data, and security breaches such as SQL injections. Validation with Vanilla Javascript can be time consuming. This is where the Joi package becomes very useful. Joi is used for validation of body, query, and URL parameters. How? Let’s look at a simple example:

*** Note: This example is building off the previous code example used for Express.

First, install Joi as a dependency in your project directory:

npm install joi

Then, create a simple POST operation in your index.js file.

const names = [];


server.post("/", (req, res) => {const name = req.body;



names.push(name);res.status(201).json(names);});

In this example, since there is no database involved, the user input is sent in the request body, and then pushed to the array of names. The array of names is then sent back as a JSON object in the response. Right now, there is no validation, so the user could send any JSON object, with any values and it would be added to the array of names. Let’s add Joi.

First import Joi into index.js:

const Joi = require('joi');

Now let’s create a schema of contraints:

const schema = {

username: Joi.string().min(3).max(25).alphanum().required();

}

Now within the post HTTP request block let’s compare the req.body and schema:



server.post("/", (req, res) => {const name = req.body;const validatedInput = Joi.validate(name, schema);



if(validatedInput.error){res.status(400).send(result.error.details)}



names.push(name);res.status(201).json(names);});

The result of the validated input is held inside of the validatedInput variable. If an error is present, it will send a response of 400 back to the user with a JSON error message with details of name constraints that have not been met. If the request body complies to all constraints specified in the schema, then the name will be pushed to the array of names and sent back to the user.

For more details and for a list of all methods, visit the API Reference at: https://github.com/hapijs/joi/blob/v13.6.0/API.md

6. Helmet

Helmet is middleware that can be added to Express to help secure an application. Helmet sets appropriate HTTP headers, that hide certain secure information from a malicious user. For example, when sending a request, a header called X-Powered-By reveals the library or framework used in the application. Although this may seem very trivial, knowing the technology used to build an application can also make it less secure. Other headers used in Helmet help by preventing man-in-the-middle attacks with forged certificates, clickjacking protection, and preventing cross-site scripting attacks.

*** Note: This code example is built off the Express example used earlier

To get started, install helmet in the project directory:

npm install helmet

Then in your index.js file import the package and then use the middleware in the server.


const helmet = require('helmet');server.use(helmet());

And that’s it! Make sure the server.use call above all requests, to ensure they are set. Check out the documentation for more information: https://helmetjs.github.io/docs/

7. Create-React-App

If you have ever built a project in React, you are most likely familiar with create-react-app. Create-React-App is a tool that was built by Facebook to help with the time-consuming setup and configuration. It sets up a local server, incorporates Babel for the latest browser features, a built in testing suite with Jest, detailed runtime errors displayed in the browser, a production build, along with many other things. Node is the only required prerequisite to installing create-react-app. All other installations are provided by the package.

You can install create-react-app globally or for one time use.



//GLOBAL INSTALLATIONnpm install create-react-app -gcreate-react-app app-name


//ONE TIME USEnpx create-react-app app-name

For more information visit the documentation at: https://github.com/facebook/create-react-app

8. Moment

Moment.js is a very popular Javascript library used for parsing, validating, manipulating, and formatting dates. This is a very popular dependency with over 4 million weekly downloads. It works for both the browser and the Node.js environment. Anytime a date needs to be displayed in a different timezone, or format you can use Moment.js for a short solution.

Here is a link to the documentation: https://momentjs.com/guides/

Go check it out the documentation and see all the examples of what Moment.js is capable of.

9. Bcryptjs

Bcrypt.js is used to hash and compare hashed passwords. It is a valuable tool to help protect passwords from rainbow table attacks. More on that here. The library creates password hashing functions, implements salting, and adding accumulating hashing rounds. In order for an attacker to access the password, they would need to access the hash, know the hashing function, and know exactly how many rounds it took to generate the hash. Lets take a look at how to implement this library.

*** Note: This example is building off the previous code example used for Express.

First install the module inside the project directory:

npm install bcryptjs

Now let’s take the previous Post request used in the Joi example above and implement hashing of the name. Here is the entire code so far:




const express = require('express')const Joi = require('joi')const bcrypt = require('bcryptjs')const helmet = require('helmet')



const server = express();server.use(helmet());server.use(express.json());



const schema = {username: Joi.string().min(3).max(25).alphanum().required();}


server.post("/", (req, res) => {const name = req.body;


const hash = bcrypt.hashSync(name.username, 10)name.username = hash;




const validatedInput = Joi.validate(name, schema);if(validatedInput.error){res.status(400).send(result.error.details)}



names.push(name);res.status(201).json(names);});

The bcrypt module is imported into the index.js file. Then the hashSync method takes in the username and the number of hashing rounds as parameters and outputs a hash that then resets the request body.

Then, later you can check the hashed value to see if it matches a username by:

bcrypt.compareSync('username', hash)

This method will either return a true or false boolean value. Check out further documentation at: https://www.npmjs.com/package/bcryptjs

Conclusion

We have concluded looking at a couple packages and examples and now I challenge you to go build a simple application utilizing each one of these libraries. Like I mentioned earlier, these are only a select few chosen packages. There are many, many more amazing packages on npm, and if I had time, I would add more to this list. Also, I would like to add, that in the examples above I barely brushed the surface of the capabilities of many of these modules. Now it is your turn to explore the documentation and write some code. Good luck, and if you have any feedback, let me know in the comments below! :)