NodeJS Package Management Tool - Getting Started with npm

        Today there is a package management tool in every language system, Composer for PHP, gem for Ruby, pip for Python, Maven for Java...and of course npm for Node.js. Some people will wonder why introduce yet another new thing to make our already hard enough programming work even worse? In fact, it is not. For example, when we are doing Java development, some projects rely on hundreds of jars. Developers always encounter various package versions before building, and the package cannot be found. However, the package management tool allows us to start from Rescue from this dependency nightmare. Any dependencies in our development process can be automatically downloaded from the remote package repository through this tool, and guaranteed to be the version we need, so we can focus on development and production.

        The only shortcoming is that the distance between my big eastern country and those foreigners' hosts is far enough that it is often impossible to download through the official mirror. There are usually three ways in this case: one is to set a proxy for the package management tool itself, and the second is to directly and globally VPN, the third is to use domestic synchronous mirroring, of course, the premise is to have it.

        Well, let’s not talk nonsense. It would be great if the following article appeared a few years ago. When I first came into contact with npm, I was dizzy enough. I hope this article can point out a straight path for beginners.

 

1. Introduction

        Node.js lets developers write server-side programs in JavaScript, and it's built on the V8 engine of JavaScript written in C++, so it's fast (do you want to say C is faster? But be aware that compared to intermediate ones written in Java) In terms of software, C++ is already fast - Translator's Note). At first, NodeJS was mainly designed for server-side application development, but slowly, developers used it to build local automation toolchains. Since then, a new NodeJS ecological environment (such as Grunt and Gulp) has been opened up, allowing a new generation of front-end developers to gradually form engineering ideas.

        In order to take advantage of these tools (or packages), we need to install and manage them in a good way (like Windows Add/Remove Programs). And so npm was born, npm installs these tools the way you want, and provides an easy-to-use interface to organize them. Before I introduce it, first install Node.js on your system.

 

2. Install Node.js

        Go to the download page of the official website to get the version you need. Both Windows and Mac have ready-made packages. For Linux platforms, precompiled binaries and source code are also prepared. Alternatively, you can install it using the package management tool for your Linux distribution.

At the time of this writing (April 3, 2016) the latest official version is v.5.10.0 stable.

Let's see how to check the installation path and version of Node:

$ which node
/usr/local/bin/node
$ node --version
v5.7.0

        Let's verify that the installation is successful by trying Node's REPL (interactive interpreter).

$ node
> console.log('Node is running');
Node is running
> .help
.break Sometimes you get stuck, this gets you out
.clear Alias for .break
.exit  Exit the repl
.help  Show repl options
.load  Load JS from a file into the REPL session
.save  Save all evaluated commands in this REPL session to a file
> .exit

        Ok, now that Node.js is installed, let's try npm. npm is already installed with Node, no additional installation is required.

$ which npm
/usr/local/bin/npm
$ npm --version
3.6.0

 

3. Install modules with Node.js

        npm can install modules individually in one of your projects or globally on your computer. When installed separately in a project, npm will download all files into a folder called node_modules in your project. The owner of this folder is the current user (in Linux, the owner permissions of the folder are sensitive, and other users cannot view files owned by another user without authorization. Although there is also this concept in Windows, usually we personally Computer users are very single, so this concept is not very important - Translator's Note). Global modules will be installed in the directory {prefix}/lib/node_modules/ owned by root user ({prefix} is usually /usr/ or /usr/local/). This means that if you want to install a module globally under a Linux distribution, you need to use the sudo command, otherwise a permission error will be raised.

1. Change the global module installation path

        First let's see what the npm config command will output

$ npm config list
; cli configs
user-agent = "npm/3.6.0 node/v5.7.0 linux x64"

; node bin location = /usr/local/bin/node
; cwd = /home/sitepoint
; HOME = /home/sitepoint
; 'npm config ls -l' to show all defaults.

        The basic configuration information of npm is listed here, the focus is here

$ npm config get prefix
/usr/local

        Lists paths to globally installed modules. We can create a new folder in our user home directory with the following command, and then change the global module installation path to this directory.

$ cd && mkdir .node_modules_global
$ npm config set prefix=$HOME/.node_modules_global

        With this, we have changed where the global module is installed. After doing the blame operation, we will also get an automatically created .npmrc file.

$ npm config get prefix
/home/sitepoint/.node_modules_global
$ cat .npmrc
prefix=/home/sitepoint/.node_modules_global

        But for developers with obsessive-compulsive disorder, this is not enough, our npm still stays in the root directory. It doesn't matter, we can reinstall npm into our local directory with the following command.

$ npm install npm --global
/home/sitepoint/.node_modules_global/bin/npm -> /home/sitepoint/.node_modules_global/lib/node_modules/npm/bin/npm-cli.js
/home/sitepoint/.node_modules_global/lib
└── [email protected]

        Well, in the last step, we add .node_modules_global/bin to the environment variable $PATH. When we enter the npm command, we will not look in the root directory, but in our own home directory.

export PATH="$HOME/.node_modules_global/bin:$PATH"

        Now we can use the which command to confirm which directory we are using npm from.

$ which npm
/home/sitepoint/.node_modules_global/bin/npm
$ npm --version
3.7.5

        ok, with this dependency, we don't need to use sudo for global installation.

 

2. Install the module globally

        For the first example, let's install a package called UglifyJS. This is a JS compression tool. We use the --global parameter to tell npm that we want to install globally. This parameter can also be abbreviated as -g

$ npm list --global
├─┬ [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
│ ├── [email protected]
....................
└─┬ [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]

        As you can see, this output is quite complicated, and when we install other packages, it may be even worse. We can use --depth=0 to tell the console to output only one level of information.

$ npm list -g --depth=0
├── [email protected]
└── [email protected]

        Well, then you can directly use the uglifyjs command to compress the file in the shell.

$ uglifyjs example.js -o example.min.js

 

3. Install the module in your own project

        Without any parameters, you can install modules in a separate project directory with the npm install command. The new package is installed into a directory called node_modules under the project folder. For example, below we locally install a module called underscore (Underscore is a JavaScript tool library that provides a full set of functional programming utilities):

$ mkdir ~/project && cd ~/project
$ npm install underscore
/home/sitepoint/project
└── [email protected]
$ ls
node_modules
$ ls node_modules
underscore

 

4. List installed modules in your own project

        We can use npm list to list the modules that have been installed in our project

$ npm list
/home/sitepoint/project
└── [email protected]

        This means that we can install another version of the underscore module in another project directory.

 

5. Uninstall the module

        Still taking underscore as an example, let's uninstall and check if the module still exists:

$ npm uninstall underscore
- [email protected] node_modules/underscore
$ npm list
/home/sitepoint/project
└── (empty)

 

6. Install a specific version of the module

        By default, npm will always look for the latest version of the package to install, but we can still specify a specific version of the module to install via an argument:

$ npm install [email protected]
/home/sitepoint/project
└── [email protected]
$ npm list
/home/sitepoint/project
└── [email protected]

 

7. Update modules

        If a package we installed before has a new version, such as fixing a bug, then we need a command to upgrade the package directly.

$ npm update underscore
[email protected] node_modules/underscore
$ npm list
/home/sitepoint/project
└── [email protected]

        Note: We need to mark underscore as a dependency in package.json for the above command to take effect. (See the "Managing Dependencies" section below)

 

8. Search Module

        We usually use the mkdir command in Linux, so is there such a package in npm that can achieve the same effect. In this scenario, we may need to search for a module with a specific function, then we can use the following command to search:

$ npm search mkdir
npm WARN Building the local index for the first time, please be patient

        We found that there really is one called mkdirp. Then let's try to install it directly

$ npm install mkdirp
/home/sitepoint/project
└─┬ [email protected]
  └── [email protected]

        Then we try to see if it is really the package we want

var mkdirp = require('mkdirp');
mkdirp('foo', function (err) {
    if (err) console.error(err)
    else console.log('Directory created!')
});

        The running result is as follows

$ node. mkdir.js
Directory created!

        ok, it was really successful~

 

4. Manage cache

        Usually, after we install a module with npm, npm will keep a copy of the installation package in the local .npm directory to speed up the installation of the same package next time. For example on Linux distributions, this directory is ~

$ ls ~ / .npm
_locks  minimist  mkdirp  registry.npmjs.org  underscore

        But over time, a lot of files will accumulate in this directory, so we need a command to clean it up.

$ npm cache clean

 

5. Manage dependencies

        Now, we have installed 2 packages, but we will definitely need more packages in the future, so it is not wise for us to install manually every time. At this time, the package.json we often see in github projects is Comes in handy. We can manage our package installations through this file. And this file can be created with the npm init command.

$ npm init
This utility will walk you through creating a package.json file.
Press ^C at any time to quit.
name: (project) demo
version: (1.0.0)
description: Demo of package.json
entry point: (index.js)
test command:
git repository:
keywords:
author: Sitepoint
license: (ISC)

        Then such a package.json file will be generated in the project root directory. We add our dependencies to this file and set some parameters:

JavaScript
{
  "name": "demo",
  "version": "1.0.0",
  "description": "Demo package.json",
  "main": "main.js",
  "dependencies": {
    "mkdirp": "^0.5.1",
    "underscore": "^1.8.3"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Sitepoint",
  "license": "ISC"
}

        The following command can omit a large section of input parameters and directly create a configuration file:

$ npm init --yes

        The name parameter in package.json will be automatically set with the folder name of your project.

        We can prevent accidentally publishing private repositories by adding the private:true configuration item, and we can prevent the warning that will be generated when executing npm install. Let's create a directory and try using package.json to download modules.

$ mkdir ~/demo && cd ~/demo
$ cp ~/project/package.json ~/demo
$ npm install
$ npm list
[email protected] /home/sitepoint/demo
├─┬ [email protected]
│ └── [email protected]
└── [email protected]

        There is a new problem. If we want to manually install a new package (without trying package.json, use the npm install command directly in the shell), how can we keep this file synchronously modified? We can use the --save parameter. For example below, we install a new package called request with the --save parameter

$ npm install request --save
$ npm list --depth=0
[email protected] /home/sitepoint/demo
├── [email protected]
├── [email protected]
└── [email protected]

        Then, our package.json file will be automatically updated to

JavaScript
"dependencies": {
  "mkdirp": "^0.5.1",
  "request": "^2.53.0",
  "underscore": "^1.8.3"
}

        You can see that the corresponding package has been added to package.json, and this whole process does not require us to modify the file.

 

PS: Version Manager

        There are several tools that allow us to use different versions of Node.js on the same machine. One of them is called n. The other is called nvm (Node Version Manager). There is a tutorial dedicated to this issue, so I won't go into details here.

 

Article source: http://www.cnblogs.com/jiuyi/p/5353676.html

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326780140&siteId=291194637