OneCompiler

Node Package Manager

342

A node package manager or NPM is a command line tool or registry of the third party libraries that we can add to our node application.

To install NPM in Ubuntu

sudo npm i -g npm@version number

The version number is optional

To check NPM is installed or to see a version of NPM

npm -v

** Package.json file **

Before we add packages to our node application we need to create a file called package.json. Package.json file is a JSON file where it stores the basic details of our application such as Project name, author, dependencies and much more. All node applications will have this package.json file. Let's see how to create a package.json file.

npm init

After hitting this command it will walk you through creating a package.json file step by step.



Let's see the basic structure of the package.json file


{
  "name": "project name",
  "description": "Project description",
  "version": "0.0.1",
  "author": "",
  "license": "ISC",
  "repository": {
    "type": "git",
    "url": ""
  },
  "engines": {
    "node": ">=8.0.0"
  },
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "@google-cloud/datastore": "1.1.0",
    "@google-cloud/storage": "^1.6.0",
    "alexa-sdk": "^1.0.25",
    "body-parser": "^1.17.2",
    "co": "^4.6.0",
    "connect": "^3.6.6",
    "cookie-parser": "^1.4.3",
    "ejs": "^2.5.6",
    "elasticsearch": "^14.1.0",
    "events": "^3.0.0",
  }
}
  • All installed packages and their dependencies are stored under node-modules folder.
  • Node packages follows semantic versioning like major.minor.patch.

Let's see some useful NPM commands

// Install a package
npm i <packageName>

// Install a specific version of a package
npm i <packageName>@<version>

// Install a package as a development dependency
npm i <packageName> —save-dev

// Uninstall a package
npm un <packageName>

// List installed packages
npm list —depth=0

// View outdated packages
npm outdated

// Update packages
npm update

- To install/uninstall packages globally, use -g flag.