A Beginner’s Guide to npm: The Node Package Manager

A Beginner’s Guide to npm: The Node Package Manager

In this article, we will discuss npm, its commands, how to install its packages, and certain versions of packages.

In this article, we will discuss npm, its commands, how to install its packages, and certain versions of packages.

Node.js allows you to write applications in JavaScript on the server. It has been written in C++ and built on V8 JavaScript runtime, which makes it fast and reliable. It was initially invented for the better server environment, but now developers use it to build tools to aid them in local task automation. After that, a new network of Node-based tools starts growing to alter the face of front-end development.

Node.js also has a vast ecosystem of libraries that are known as NPM (Node Package Manager) modules. It is considered as the most extensive software packages library in the world having over 600,000 packages. The npm allows users to install the packages that they want to use with a user-friendly interface. The Node.js installation comes with Command Line Interface that allows users to interact with the packages on their local machine.

In this article, we will discuss npm, its commands, how to install its packages, and certain versions of packages. Also, we will talk about package.json and how you can work with it.

What Is npm?

npm stands for Node Package Manager and it works as a project manager for JavaScript. However, it is actually defined in three different parts:

  1. The Website – It is the place where users can browse packages, read the docs, and find general info on npm.
  2. The Registry – It is the database that stores the information and the code for the packages.
  3. The npm Client – It is the tool installed on the developer’s machine to allow them to install, publish, and update packages.

It is considered as a package because it contains multiple files.

Installing Node.js

To use npm, first, you’ll have to install Node.js on your system. Download Node.js and select the version that you want to install on your system. You can find Windows and Mac installers, as well as precompiled Linux libraries and source code. Here, we have used v10.15.3 stable for installing Node.js.

So, let’s see where node.js is installed and check the version:

$ which node

/usr/bin/node

$ node –version

V10.15.3

Now, to verify whether the installation was successful or not, give Node’s REPL a try.

$ node

> console.log('Node is running');

Node is running

> .help

.break Sometimes you get stuck, this gets you out

.clear Alias for .break

.editor Enter editor mode

.exit Exit the repl

.help Show repl options

.load Load JS from a file into the REPL session

.save Save all evaluated commands in this REPL session to a file

> .exit

If the Node.js is successfully installed, you can focus on using npm that is installed within the Node.js package.

$ which npm

/usr/bin/npm

$ npm --version

6.4.1

Working With npm

For modern web development, using npm is no less than a cornerstone, even if it comes as a package manager with Node.js exclusively or build tool for the front-end. For beginners, especially if you’re completely new to Node.js, it can be a bit challenging to understand npm as a tool and its core concepts. But, we still tried to briefly review it in the best and easiest way for you.

Introduction to package.json

Any project that uses Node.js needs to have a package.json file that is known as a patent of your project, which involves the modules and applications it depends on, source control information, and specific metadata like the project’s name, explanation, and source.

A package.json file is always formatted in JSON format to make it readable as metadata and parsable by machines.

Project Dependencies and devDependencies Management in package.json

Another crucial feature of package.json is that it includes a collection of dependencies on which a project relies to function properly. These dependencies make it easy for a project to install the versions of the modules it depends on. By using the install command (discussed in the below part) in a project, developers can install all the dependencies that are included in the package.json, which means you don’t have to bundle them with the project itself.

Also, it separates the dependencies of production and development. For instance, in production, you don’t need a tool to look after your CSS for changes and refresh the app when they are modified, but in both production and development you need the modules that allow you to accomplish certain things with your project, like API Tools, Web framework, and code utilities.

Here is an example of package.json with dependencies and devDependencies.

{
"name": "metaverse",
"version": "0.92.12",
"description": "The Metaverse virtual reality. The final outcome of all virtual worlds, augmented reality, and the Internet.",
"main": "index.js"
"license": "MIT",
"devDependencies": {
	"mocha": "~3.1",
	"native-hello-world": "^1.0.0",
	"should": "~3.3",
	"sinon": "~1.9"
},
"dependencies": {
"	fill-keys": "^1.0.2",
	
	"module-not-found-error": "^1.0.0",
	"resolve": "~1.1.7"
	}
}

However, both the package.json dependencies and devDependencies are objects with multiple key/value pairs. The key refers to the name of the package, whereas the value refers to version range that can be installed.

Essential Commands of npm

As mentioned above, npm comes with a command line interface, which means you’ll have to use a command line tool for most of your interactions. So, here is an overview of commands that you’ll have to use most frequently.

  • npm init for initializing a project.

It is a step-by-step tool command that frames out your project. It prompts the user for a few aspects of the project in the following order:

  • npm init for initializing a project.

Well, it is necessary to know that the npm init command provides suggestions next to the prompt, so if you want to use the suggestions, then hit the Return or Enter button to move to the next prompt.

When you follow the above steps of npm init, it will generate a package.json file and place it in the current directory. You can run this file for your own project or move it to a directory that is not dedicated to your project.

To use the npm init command, use the below command:

npm init # This will trigger the initialization.

However, if you want to accept the prompts that come from npm init automatically, then use the –yes flag on the npm init command. It will populate all the options automatically with the default npm init values.

npm Modules and Their Installation

As described earlier, the npm library is very extensive, which makes it difficult for users to find the right modules and tools for your application. So, here we have tried to cover the most useful modules for development.

1. Nodemon

It is a useful command line interface utility that is used in the development stage of the application. Usually, when changes are made to an application, developers need to restart the server manually. Using Nodemon, this process can be alleviated as it wraps the Node application, watches for file changes, and then restarts the server automatically whenever changes are made to it. You can install this module with the following command:

npm install Nodemon –save-dev

Then, restart the server in the command prompt with nodemon:

nodemon index.js

2. Express

Express is a web application framework that wraps a Node.js web server. It provides simple API, routing, and middleware functions. It is normally used for RESTful APIs, single page application serving, and static content serving. To install the Express module, use the following command:

npm install express

Once express is installed, create an index.js file in your root folder with the following code:

const express = require('express');
const server = express();
server.use(express.json());
server.listen(5000, () => {
	console.log("Server running at port 5000")
});

After running the above code, go to the command line in your project directory and add:

node index.js

The express server will be created in your directory and it will be connected to localhost.

3. Helmet

Helmet is a middleware module that can be used with Express to secure an application. It sets appropriate HTTP headers that hide secure information from malicious users or malware attacks. Other headers in Helmet prevent malicious users from accessing crucial information with forget certificates and prevent cross-site scripting attacks. You can install the Helmet module in the project library with the following command:

npm install helmet

Then, import the package in your index.js file and use the middleware in the server with the following code:

const helmet = require (‘helmet’);
Server.use (helmet());

But, make sure all the requests in your server are set so that server.use can call the requests.

Similarly, you can install other npm packages to your server. But, it is necessary to know that npm can install packages in local and global mode. In local mode, the above method is used, whereas, in global mode packages are installed in {prefix}/lib/node_modules/ which means you’ll have to use sudo to install packages globally.

Changing Location of Global Packages

If you want to change the location of global packages, then you can use the npm config.

$ npm config list
; cli configs
user-agent = "npm/6.9.0 node/v10.15.3 linux x64"
; userconfig /home/sitepoint/.npmrc
prefix = "/home/sitepoint/.node_modules_global"
; node bin location = /usr/bin/nodejs
; cwd = /home/sitepoint
; HOME = /home/sitepoint
; "npm config ls -l" to show all defaults.

It will provide you with the information related to installation, but you need to get the current global location of the packages, which can be achieved with:

$ npm config get prefix
/usr

You’ll have to use the above prefix to install global packages in the home directory. For that, create a new directory in the home folder:

$ cd ~ && mkdir .node_modules_global
$ npm config set prefix=$HOME/.node_modules_global

With this configuration change, you can alter the location to where global Node packages are installed. It will also create a .npmrc file in the home directory.

$ npm config get prefix
/home/sitepoint/.node_modules_global
$ cat .npmrc
prefix=/home/sitepoint/.node_modules_global
$ npm config get prefix
/home/sitepoint/.node_modules_global
$ cat .npmrc
prefix=/home/sitepoint/.node_modules_global

If you still have npm installed in a location owned by the root directory, then you need to install npm again. It will also install the latest version of npm.

npm install [email protected] -g

At last, you need to add .node_modules_global/bin to the $PATH environment variable so that you can run global packages from the command line.

Top 7 Most Popular Node.js Frameworks You Should Know

Top 7 Most Popular Node.js Frameworks You Should Know

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser. In this post, you'll see top 7 of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser.

One of the main advantages of Node is that it enables developers to use JavaScript on both the front-end and the back-end of an application. This not only makes the source code of any app cleaner and more consistent, but it significantly speeds up app development too, as developers only need to use one language.

Node is fast, scalable, and easy to get started with. Its default package manager is npm, which means it also sports the largest ecosystem of open-source libraries. Node is used by companies such as NASA, Uber, Netflix, and Walmart.

But Node doesn't come alone. It comes with a plethora of frameworks. A Node framework can be pictured as the external scaffolding that you can build your app in. These frameworks are built on top of Node and extend the technology's functionality, mostly by making apps easier to prototype and develop, while also making them faster and more scalable.

Below are 7of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Express

With over 43,000 GitHub stars, Express is the most popular Node framework. It brands itself as a fast, unopinionated, and minimalist framework. Express acts as middleware: it helps set up and configure routes to send and receive requests between the front-end and the database of an app.

Express provides lightweight, powerful tools for HTTP servers. It's a great framework for single-page apps, websites, hybrids, or public HTTP APIs. It supports over fourteen different template engines, so developers aren't forced into any specific ORM.

Meteor

Meteor is a full-stack JavaScript platform. It allows developers to build real-time web apps, i.e. apps where code changes are pushed to all browsers and devices in real-time. Additionally, servers send data over the wire, instead of HTML. The client renders the data.

The project has over 41,000 GitHub stars and is built to power large projects. Meteor is used by companies such as Mazda, Honeywell, Qualcomm, and IKEA. It has excellent documentation and a strong community behind it.

Koa

Koa is built by the same team that built Express. It uses ES6 methods that allow developers to work without callbacks. Developers also have more control over error-handling. Koa has no middleware within its core, which means that developers have more control over configuration, but which means that traditional Node middleware (e.g. req, res, next) won't work with Koa.

Koa already has over 26,000 GitHub stars. The Express developers built Koa because they wanted a lighter framework that was more expressive and more robust than Express. You can find out more about the differences between Koa and Express here.

Sails

Sails is a real-time, MVC framework for Node that's built on Express. It supports auto-generated REST APIs and comes with an easy WebSocket integration.

The project has over 20,000 stars on GitHub and is compatible with almost all databases (MySQL, MongoDB, PostgreSQL, Redis). It's also compatible with most front-end technologies (Angular, iOS, Android, React, and even Windows Phone).

Nest

Nest has over 15,000 GitHub stars. It uses progressive JavaScript and is built with TypeScript, which means it comes with strong typing. It combines elements of object-oriented programming, functional programming, and functional reactive programming.

Nest is packaged in such a way it serves as a complete development kit for writing enterprise-level apps. The framework uses Express, but is compatible with a wide range of other libraries.

LoopBack

LoopBack is a framework that allows developers to quickly create REST APIs. It has an easy-to-use CLI wizard and allows developers to create models either on their schema or dynamically. It also has a built-in API explorer.

LoopBack has over 12,000 GitHub stars and is used by companies such as GoDaddy, Symantec, and the Bank of America. It's compatible with many REST services and a wide variety of databases (MongoDB, Oracle, MySQL, PostgreSQL).

Hapi

Similar to Express, hapi serves data by intermediating between server-side and client-side. As such, it's can serve as a substitute for Express. Hapi allows developers to focus on writing reusable app logic in a modular and prescriptive fashion.

The project has over 11,000 GitHub stars. It has built-in support for input validation, caching, authentication, and more. Hapi was originally developed to handle all of Walmart's mobile traffic during Black Friday.

How to Install Node.js with npm on Debian 10

How to Install Node.js with npm on Debian 10

Install Node.js with npm on Debian 10 In this tutorial, we are going to learn how to install Node.js with npm on Debian 10

Table of Contents

Install Node.js with npm on Debian 10

In this tutorial, we are going to learn how to install Node.js with npm on Debian 10. Node.js is the opensource JavaScript Run-time environment for server-side execution of JavaScript code. Node.js built on Chrome’s V8 JavaScript engine so it can be used to build different types of server-side applications.

Where npm stands for Node Package Manager which is the default package manager for Node.js. npm is the world’s largest software registry for Node.js packages with thousands of packages available.

In this tutorial we will install Node.js in following two ways:

  1. Install Node.js and npm using Debian repository
  2. Install Node.js and npm using nvm
  3. Install Node.js from the NodeSource repository.

1. Install Node.js and npm using Debian repository

First, Update Debian apt package manager index by running the following command.

sudo apt update

Install Node.js from Debian global repository by typing

sudo apt install node

Confirm the installation of Node.js by typing

node --version

Install npm by running following command

sudo apt install npm

Confirm the installation of npm by typing

npm --version

2. Install Node.js and npm using nvm

NVM stands for Node Version Manager which is used to manage multiple Node.js versions. If you want to install or uninstall different versions of Node.js then NVM is there for you.

First, we will install NVM (Node Package Manager) on your system. So download the NVM installation script running the following command.

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash

Check nvm version and confirm installation typing

node --version

Now install Node.js by using the following command.

nvm install node

Verify Node.js installation by typing

node --version

The output should be:

Output

v10.14.0

You can install multiple versions of Node.js. To do so type the following:

nvm install 8.14
nvm install --lts
nvm install 11.3

To list all the versions installed run following command.

nvm ls

You can change the current default version of Node.js by using the following command.

nvm use 8.14

To uninstall a Node.js version type following command

nvm uninstall 11.14

Install Node.js from NodeSource Repository

NodeSource company provides enterprise-grade node support also maintains the repository containing the latest version of Node.js.

To enable the NodeSource repository on your system run following command.

curl -sL https://deb.nodesource.com/setup_10.x | sudo bash -

NOTE: The latest LTS version of Node.js is 10.x if you want to install 8.x version then just replace setup_10.x with setup_8.x

Now install Node.js and npm package typing.

sudo apt install nodejs

Verify installation of Node.js and npm running following command

node --version
npm --version

Install Development Tools

Now install some packages needed for development by running following command

sudo apt install gcc g++ make

Uninstall Node.js and npm

Uninstall Node.js use following command

sudo apt remove nodejs npm
sudo apt autoremove

To uninstall node.js version using nvm type following command

nvm uninstall 10.14

Conclusion

You have successfully learned how to install Node.js with npm on Debian 10. If you have any queries don’t forget to comment below.

Hashing Passwords with Node.js and NPM Bcrypt Library

Hashing Passwords with Node.js and NPM Bcrypt Library

In this tutorial, we will learn to use NPM bcryptjs library to hash and compare the passwords in Node.js

In this tutorial, we will learn to use NPM bcryptjs library to hash and compare the passwords in Node.

To create a secure application, it is always considered a safe practice not to store a user’s password in the database in plain text format. If not in plain text format, then what else we can do?

Here is the solution, generate a hash (complex string and numbers) and store that hash in the database. You can decipher your hashed password later by using the comparing method.

Let’s assume if there was a breach in your database, and all your stored passwords were leaked. Then, you are at significant risk, and password hashing is the best one-way encryption technique to secure the passwords.

In this method, you do not store users’ passwords in the database in its original form. Instead, a password is stored in a complex combination of text and unique characters; this is known as a password hash method.

A hacker can not easily decipher an adequately hashed password. Hackers will get frustrated because it will take lots of time and effort to decrypt the password.

In this tutorial, we will learn how to install and correctly hash a password in node.js.

We will take the help of the NPM BcryptJs package, and it is a widely used encryption module available nowadays via NPM.

Before we begin, you must have Node.js configured in your machine. If not, then you can check out how to install Node in your system tutorial.

Install bcryptjs Npm Module

To get started i assume you already have a Node.js project setup along with Express, and MongoDB.

Run one of the command based on your package manage.

# npm
npm install bcryptjs --save

# yarn
yarn add bcryptjs

Now, once bcryptjs successfully installed. We are ready to go ahead!

Hash A Password with Bcrytp Js

To get started with hashing the password we need node server configuration. In the app.js file, we imported express, bodyParser, mongoose and bcrytpjs module. We defined the MongoDB database connection, user schema and two REST APIs for registering and signing in the user.

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const bodyParser = require('body-parser');

// Express APIs
const api = require('./routes/auth.routes');

// MongoDB conection
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/nodedb", {
    useNewUrlParser: true,
    useUnifiedTopology: true
}).then(() => {
    console.log('Database connected')
},
    error => {
        console.log("Database can't be connected: " + error)
    }
)

// Express settings
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(cors());

app.use('/api', api)

// Define PORT
const port = process.env.PORT || 4000;
const server = app.listen(port, () => {
    console.log('Connected to port ' + port)
})

// Express error handling
app.use((req, res, next) => {
    setImmediate(() => {
        next(new Error('Something went wrong'));
    });
});

app.use(function (err, req, res, next) {
    console.error(err.message);
    if (!err.statusCode) err.statusCode = 500;
    res.status(err.statusCode).send(err.message);
});

Hashing a password is very simple, the first argument in the bcrypt.hashSync() method is the password which we are getting from req.body middleware. The second argument is the number of rounds which we set to 10 to generate a salt.

// routes/auth.routes.js

const express = require("express");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
const router = express.Router();
const userSchema = require("../models/User");

// Sign-up
router.post("/signup", (req, res, next) => {
    bcrypt.hash(req.body.password, 10).then((hash) => {
        const user = new userSchema({
            name: req.body.name,
            email: req.body.email,
            password: hash
        });
        user.save().then((response) => {
            res.status(201).json({
                message: "User successfully created!",
                result: response
            });
        }).catch(error => {
            res.status(500).json({
                error: error
            });
        });
    });
});

So we are hashing the password when the user makes the signup call after that we are creating a user instance and saving the user data along with the password in the MongoDB database.

Verify or Compare The Password with Bcrypt

When the user logs in the app, API will check the if the email exists in the database with the help of userSchema.findOne() method. Then, we will validate the stored password with the help of bcrypt.compareSync() method. It takes two passwords as an argument stored password and user-entered password.

// routes/auth.routes.js

const express = require("express");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
const router = express.Router();
const userSchema = require("../models/User");

// Sign-in
router.post("/signin", (req, res, next) => {
    let getUser;
    userSchema.findOne({
        email: req.body.email
    }).then(user => {
        if (!user) {
            return res.status(401).json({
                message: "Authentication failed"
            });
        }
        return bcrypt.compare(req.body.password, user.password);
    }).then(response => {
        if (!response) {
            return res.status(401).json({
                message: "Authentication failed"
            });
        }
    }).catch(err => {
        return res.status(401).json({
            message: "Authentication failed"
        });
    });
});
Conclusion

We have seen how to store the password in the database securely by making the REST API call with Node/Express.