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.
Join the DZone community and get the full member experience.
Join For FreeNode.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:
The Website – It is the place where users can browse packages, read the docs, and find general info on npm.
The Registry – It is the database that stores the information and the code for the packages.
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:
Project’s name.
Project’s initial version.
Project’s description.
Project’s entry point (main file).
Project’s test command.
Project’s git repository (for project source).
Project’s keywords related to the project.
Project’s license.
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 npm@latest -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.
Opinions expressed by DZone contributors are their own.
Comments