In many ways, the success of Node.js is due to growth in the number and quality of packages available to the developer community, distributed via the Node package management system (NPM).
NPM is a Node package management system and online repository for publishing open-source Node.js custom or user-created packages. It is also a command-line utility for interacting with the online repository that aids in package installation, version management, and dependency management.
In creating a custom package, you can make it private or public for others. We will not cover private packages in this guide, but we will learn how to install, update, and run scripts using NPM.
Installing packages
To install any package into your Node.js project, you need the full name of the package you want to install, then use it with the command as shown below:
npm install is-even
npm
is the package manager and a command line utility, install
is the command we want to run, which takes in is-even
as the name of the package we will pull from the online repository and install into our local repository and project.
Updating a package
Assuming you want to update the version of a package you installed earlier. You can use the following command to achieve it.
npm update [email protected]
You can update a specific package by specifying the version number or update all packages using npm update
command.
Running your Node project
Professionally, when creating a Node project, you include a package.json file to manage your dependencies and some project metadata. You can create a blank package.json
file using the following command:
npm init -y
Specifying the -y
flag means you want to accept all the defaults. Now, you can add a script section on your package.json
file to run some commands using NPM. Let’s take a look at how to run a Node project using NPM:
{
"name": "tests",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \\"Error: no test specified\\" && exit 1",
"start": "node index.js"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Look at the script above. The start
property inside the scripts
object tells NPM how to start the Node project. Running the start
command using NPM will start our Node project:
npm run start
You can specify as many commands you want to run in the scripts
section and run it using the run
command in NPM.