Nodejs Npm
NPM (Node Package Manager) is a JavaScript package management tool and the default package manager for Node.js.
NPM allows developers to easily download, install, share, and manage project dependencies and tools.
NPM is the built-in package manager for Node.js; therefore, installing Node.js usually automatically installs NPM on your system.
!(#)
**Main Features:**
* **Package Management**: NPM helps you install and manage various third-party libraries (packages) required by your projects. For example, you can install, update, or remove dependencies using simple commands.
* **Version Management**: NPM supports version control, allowing you to lock dependencies to specific versions or choose the latest version as needed.
* **Package Publishing**: NPM allows developers to publish their own libraries to the NPM registry so other developers can download and use them via NPM.
* **Command-Line Tools**: NPM provides powerful command-line tools for tasks such as installing packages, running scripts, and initializing projects.
Since newer versions of Node.js come bundled with NPM, you can directly test whether NPM was successfully installed by entering `npm -v`. If the version number appears, the installation was successful:
$ npm -v 2.3.0
If you have an older version of npm installed, you can easily upgrade it using the npm command as follows:
$ sudo npm install npm -g /usr/local/bin/npm -> /usr/local/lib/node_modules/npm/bin/npm-cli.js npm@2.14.2 /usr/local/lib/node_modules/npm
For Windows systems, use the following command instead:
npm install npm -g
* * *
## Installing Modules Using npm Commands
The syntax for installing Node.js modules with npm is as follows:
$ npm install
In the following example, we use the npm command to install the popular Node.js web framework module **express**:
$ npm install express
After installation, the express package will be placed in the `node_modules` directory under your project folder. Therefore, in your code, you only need to reference it using **require('express')**, without specifying the path to the third-party package.
var express = require('express');
* * *
## Global vs. Local Installation
npm package installation is divided into two types: local installation and global installation. The difference lies solely in whether or not the `-g` flag is used in the command.
**Local Installation:** Installs the package into the `node_modules` directory and saves information into the `dependencies` section of `package.json`.
npm install express # local installation
**Global Installation:** Used for installing command-line tools or packages needed across multiple projects.
npm install express -g # global installation
If you encounter the following error:
npm err! Error: connect ECONNREFUSED 127.0.0.1:8087
The solution is:
$ npm config set proxy null
### Local Installation
* **Scope**: By default, npm installs packages into the `node_modules` folder of the current project. This means each project using that package will maintain its own copy.
* **Purpose**: Local installations are typically used for project dependencies. Each project can specify its own dependency versions, helping ensure stability and reproducibility.
* **Installation Command**: Running `npm install ` inside a project directory installs the package into the `node_modules` folder and adds the dependency to the `package.json` file.
* **Version Management**: Dependency versions are managed through `package.json` and `package-lock.json`, ensuring consistency across different environments.
### Global Installation
* **Scope**: Global installation places packages in a system-level directoryβtypically `/usr/local/bin` on Unix-like systems or `%AppData%npm` on Windows.
* **Purpose**: Global installation is intended for tools or command-line utilities that do not need to be reinstalled in every projectβfor example, installing a global `create-react-app` utility to bootstrap new React projects.
* **Installation Command**: Use the `-g` flag to globally install a package, e.g., `npm install -g `.
* **Version Management**: Versions of globally installed packages are managed by npm but are not reflected in the projectβs `package.json`. This means globally installed packages may be shared across projects but could also cause conflicts due to incompatible versions.
| Feature | Local Installation | Global Installation |
| --- | --- | --- |
| **Installation Scope** | Available only within the current project | Available system-wide |
| **Command Usage** | `npm install package-name` | `npm install -g package-name` |
| **Installation Location** | `node_modules` directory | System global directory (OS-dependent) |
| **Use Cases** | Project dependencies (libraries, frameworks) | CLI tools, project generators |
| **Access Method** | Used via `require()` or `import` | Used directly from the command line |
| **Dependency Declaration** | Recorded in `package.json` | Not recorded in `package.json` |
| **Version Control** | Different versions allowed per project | Only one version retained system-wide |
| **Permission Requirements** | No special permissions required | May require administrator privileges |
If you wish to support both modes, youβll need to install the package in both locations or use **npm link**.
Next, letβs install express globally:
$ npm install express -g
The installation output looks like this, where the first line shows the moduleβs version and installation location.
express@4.13.3 node_modules/express βββ escape-html@1.0.2βββ range-parser@1.0.2βββ merge-descriptors@1.0.0βββ array-flatten@1.1.1βββ cookie@0.1.3βββ utils-merge@1.0.0βββ parseurl@1.3.0βββ cookie-signature@1.0.6βββ methods@1.1.1βββ fresh@0.3.0βββ vary@1.0.1βββ path-to-regexp@0.1.7βββ content-type@1.0.1βββ etag@1.7.0βββ serve-static@1.10.0βββ content-disposition@0.5.0βββ depd@1.0.1βββ qs@4.0.0βββ finalhandler@0.4.0 (unpipe@1.0.0)βββ on-finished@2.3.0 (ee-first@1.1.1)βββ proxy-addr@1.0.8 (forwarded@0.1.0, ipaddr.js@1.0.1)βββ debug@2.2.0 (ms@0.7.1)βββ type-is@1.6.8 (media-typer@0.3.0, mime-types@2.1.6)βββ accepts@1.2.12 (negotiator@0.5.3, mime-types@2.1.6)βββ send@0.13.0 (destroy@1.0.3, statuses@1.2.1, ms@0.7.1, mime@1.3.4, http-errors@1.3.1)
### Viewing Installation Information
You can list all globally installed modules using the following command:
$ npm list -g βββ¬ cnpm@4.3.2β βββ auto-correct@1.0.0β βββ bagpipe@0.3.5β βββ colors@1.1.2β βββ¬ commander@2.9.0β β βββ graceful-readlink@1.0.1β βββ¬ cross-spawn@0.2.9β β βββ lru-cache@2.7.3β¦β¦
To check the version number of a specific module, use the following command:
$ npm list grunt projectName@projectVersion /path/to/project/folder βββ grunt@0.4.1
* * *
## Uninstalling Modules
You can uninstall Node.js modules using the following command:
$ npm uninstall express
After uninstallation, you can verify whether the package still exists under the `/node_modules/` directory, or alternatively run:
$ npm ls
* * *
## Updating Modules
You can update modules using the following command:
$ npm update express
* * *
## Searching for Modules
Use the following command to search for modules:
$ npm search express
* * *
## Creating Modules
Creating a module requires a `package.json` file. You can generate this file using NPMβthe resulting file contains basic structure and metadata.
$ npm init This utility will walk you through creating a package.json file.It only covers the most common items, and tries to guess sensible defaults.See `npm help json` for definitive documentation on these fields and exactly what they do.Use `npm install --save` afterwards to install a package and save it as a dependency in the package.json file.Press ^C at any time to quit. name: (node_modules) # Module name version: (1.0.0) description: Node.js Test Module(www..com) # Description entry point: (index.js) test command: make test git repository: # Github URL keywords: author: license: (ISC) About to write to β¦β¦/node_modules/package.json: # Generation path{ "name": "", "version": "1.0.0", "description": "Node.js Test Module(www..com)", β¦β¦}Is this ok? (yes) yes
You must input the above information according to your own requirements. After typing "yes" at the end, the `package.json` file will be generated.
Next, register a user in the npm registry (using your email address) with the following command:
$ npm adduser Username: mcmohd Password:Email: (this IS public) mcmohd@gmail.com
Then publish your module using the following command:
$ npm publish
If all the above steps are completed correctly, others can install your module just like any other npm package.
* * *
## Version Numbers
You'll frequently encounter version numbers when downloading and publishing code via NPM. NPM uses Semantic Versioning (SemVer) to manage versionsβhere's a brief introduction.
Version numbers follow the semantic versioning format: MAJOR.MINOR.PATCH, optionally followed by additional identifiers.
* **MAJOR (Major Version)**: Incremented when making incompatible API changes. Example: `2.0.0`.
* **MINOR (Minor Version)**: Incremented when adding backward-compatible features. Example: `1.1.0`.
* **PATCH (Patch Version)**: Incremented when making backward-compatible bug fixes. Example: `1.0.1`.
### Additional Identifiers
* **Pre-release Versions**: Such as `1.0.0-alpha` or `1.0.0-beta.1`, indicating the release is still under testing.
* **Build Metadata**: Such as `1.0.0+build.1`, providing build-related information.
### Installation Examples
* Install a specific version: `npm install package-name@1.2.3`
* Install the latest compatible major version: `npm install package-name@^1.2.3` (installs the latest `1.x.x` version)
* * *
## Common NPM Commands
NPM provides many commands; you can view all available commands using `npm help`.
| Command | Description |
| --- | --- |
| `npm init` | Initializes a new `package.json` file interactively. |
| `npm init -y` | Quickly creates a `package.json` file with default settings. |
| `npm install package-name` | Installs the specified package locally. |
| `npm insta
YouTip