How to install third party packages using npm

Node.jsServer Side ProgrammingProgramming

Now, so far we saw how to create a node project with npm init command and also adding scripts to run application.

Why third party libraries are required

We used core modules of node.js like http, fs etc which are available by default with node.js but working only with these core modules does not simplify our work. To add more useful functionality and simpler code we requires to install third party libraries like express, body-parser etc.

We get the third party libraries from cloud stored npm repository. Installation is done using npm install command.

Nodemon

We are running our App.js file using npm start command. But whenever we do change our code, we have to stop server using ctrl + c and then restart using npm start to make available those changes.

To make things simpler, we have third party package called nodemon to auto restart whenever changes are added automatically.

Dependencies which are required in production environment are categorized as just dependencies and the other libraries which are required only in development mode are categorized as de dependencies.

To install a library as dev dependency we used –save-dev in our npm install command.On installation complete package.json file looks like −

{
   "name": "dev",
   "version": "1.0.0",
   "description": "",
   "main": "App.js",
   "scripts": {
      "test": "echo \"Error: no test specified\" &&
      exit 1",
      "start": "node App.js"
   },
   "author": "",
   "license": "ISC",
   "devDependencies": {
      "nodemon": "^2.0.3"
   }
}

package.json file shows the installed version of nodemon.

With the addition of first third party library, we also get a folder named Node Modules and file package-lock.json

Package-lock.json maintains the internal tree hierarchy of libraries which are dependent on each other.

^ in version number of nodemon is for deciding latest version ,how nodemon will be installed in any other systems on npm install.

How to use nodemon −

In our npm scripts section we have npm start command −

"scripts": {
   "test": "echo \"Error: no test specified\" && exit 1",
   "start": "node App.js"
},

Start command will need to change −

"scripts": {
   "test": "echo \"Error: no test specified\" && exit 1",
   "start": "nodemon App.js"
},

Now, we can run app using npm start and it will also auto restart on any code change save.

raja
Published on 13-May-2020 12:17:13
Advertisements