npm is the package manager for node.js. npm (node package manager) runs through the command line and manages dependencies for an application.
Let’s look into an example
For this we create two files “npm.js” and “package.json
npm.js :
var express = require('express'), mongodb = require('mongodb'), cons = require('conslidate');
Package.json :
{ "name" : "intro_to_npm", "version" : "0.0.0", "description" : "npm instruction", "main" : "npm.js", "dependencies": { "consolidate" : "~0.9.1", "mongodb" : "~1.3.10", "express" : "~4.9.8" }, "author" : "Deepak", "license": "BSD" }
Now look at npm.js. If you compile npm.js with node.js
$ nodejs npm.js
It pop up an error message something like this :
Error: Cannot find module 'express'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (C:ChatServerServerserver.js:6:9)
at Object.<anonymous> (C:ChatServerServerserver.js:25:4)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
It describes that in npm.js file we are asking for “express” but it is not yet install or present. So in order to get rid of this error install express
$ npm install express
Similarly if we run it again it again pop-up an error for “consolidate”, as it ask to install “consolidate” package and so on. Instead of getting or facing error everytime we create a file called “package.json” in which we added everything which like
"consolidate" : "~0.9.1", "mongodb" : "~1.3.10", "express" : "~4.9.8"
if we run
$ npm install
It will automatically finds .json file and install all dependencies. And this will install local modules in local modules directory named “node_modules”. You can check node_modules directory in order to check whether all required packages are installed or not.