NodeJS and NPM are often talked side by side. In JavaScript, we can write any functionality as a module. These modules are known as Node Modules. You can publish these modules to NPM which is an online registry for node module distribution. So basically, NPM (Node Package Manager) is a command line utility installed along with NodeJS and is used to install JavaScript modules or node modules from an online registry. We won’t go into the history about, how frontend community ended up with NPM but the community has evolved a lot and went through many options for module or library distribution. Now, NPM is what people use to install and use third part JavaScript library.
Package.json
Almost all frontend projects now contain a package.json file. what is it and why do we need it? Basically, it is a JSON file containing information about the project. Initially, you need package.json file if you want to create a sharable NPM module and publish it on NPM registry. This file contains information about the module and list of dependencies on other node modules. But community has started using NPM more than just a package manager like it is used to run build scripts, invoke workflows etc…
So now, you will see package.json file in most of the frontend projects even if the project is not a sharable NPM module.
NPM Commands
Check installation
npm -v
Create package.json file
npm init -y
It generates package.json file with default values. Package name will be the folder name where the command is executed.
Install NPM with global scope
npm install -g <module name>
-g flag is for global scope. Usually, NPM exposed as command line utility should be installed in global scope so that it can be accessed from anywhere in system. These modules are downloaded in machine’s HOME folder’s .npm directory.
List of installed NPMs in global scope
npm ls -g --depth=0
List of outdated NPMs in global scope
npm outdated -g
It list down all the outdated NPMs currently installed version and available latest version.
Install NPM with local scope and save info in package.json
npm install --save <module name>
It downloads NPM module from online registry and save it in node_modules folder in current directory. —save flag updates the package.json file with installed module name and version.
Execute NPM script
npm run <npm script>
It executes any command mentioned in scripts section of package.json
Summary
NPM is an online registry of node modules
NPM is a command line utility installed with NodeJS
Package.json is the file contains information about module and it’s dependencies over other node modules.