Node.js Part 5 Guide: npm and npx

Original author: Flavio Copes
  • Transfer
  • Tutorial
Today, in the fifth part of the translation guide for Node.js, we will complete the analysis of npm features, in particular, we will touch on such issues as finding out the installed versions of npm-packages, installing old versions of packages, updating dependencies, local and global uninstalling packages. Here we will talk about npx.




Finding out the versions of installed npm packages


To find out the versions of all npm packages installed in the project folder, including their dependencies, run the following command:

npm list

As a result, for example, the following can happen:

> npm list
/Users/flavio/dev/node/cowsay
└─┬ cowsay@1.3.1
  ├── get-stdin@5.0.1
  ├─┬ optimist@0.6.1
  │ ├── minimist@0.0.10
  │ └── wordwrap@0.0.3
  ├─┬ string-width@2.1.1
  │ ├── is-fullwidth-code-point@2.0.0
  │ └─┬ strip-ansi@4.0.0
  │   └── ansi-regex@3.0.0
  └── strip-eof@1.0.0

The same can be recognized by viewing the package-lock.jsonproject file , but the tree structure that the above command displays is more convenient to view.

To get a similar list of packages installed globally, you can use the following command:

npm list -g

You can only display information about local top-level packages (that is, those that you installed on your own and that are listed in package.json) by:

npm list --depth=0

As a result, if, for example, you installed only the cowsay package, the following will be displayed:

> npm list --depth=0
/Users/flavio/dev/node/cowsay
└── cowsay@1.3.1

To find out the version of a particular package, use the following command:

npm list cowsay

As a result of its implementation, you get something like the following:

> npm list cowsay
/Users/flavio/dev/node/cowsay
└── cowsay@1.3.1

This command is also suitable for finding out the dependency versions of the packages you have installed. In this case, the name of the dependency package appears as the name of the packet transmitted to it, and the output of the command will look like this:

> npm list minimist
/Users/flavio/dev/node/cowsay
└─┬ cowsay@1.3.1
  └─┬ optimist@0.6.1
    └── minimist@0.0.10

The package dependency entry in this structure will be highlighted.

If you want to find out what is the latest version of a certain package available in the npm repository, you will need the following command:

npm view [package_name] version

In response, it gives the version number of the package:

> npm view cowsay version1.3.1

Installing old versions of npm packages


Installing an old version of the npm package may be needed to resolve compatibility issues. You can install the required version of the package from npm using the following construction:

npm install <package>@<version>

In the case of the cowsay package used by us as an example, the npm team will install cowsayinstall its latest version (1.3.1 at the time of this writing). If you need to install its version 1.2.0, use the following command:

npminstallcowsay@1.2.0

You can specify the version and installing global packages:

npminstall-gwebpack@4.16.4

If you need to know which versions of a certain package are available in npm, you can do this with the following design:

npm view <package> versions

Here is an example of the result of her work:

> npm view cowsay versions
[ '1.0.0',
  '1.0.1',
  '1.0.2',
  '1.0.3',
  '1.1.0',
  '1.1.1',
  '1.1.2',
  '1.1.3',
  '1.1.4',
  '1.1.5',
  '1.1.6',
  '1.1.7',
  '1.1.8',
  '1.1.9',
  '1.2.0',
  '1.2.1',
  '1.3.0',
  '1.3.1' ]

Upgrade project dependencies to their latest versions.


When you install a package with the view command npm install <packagename>, the latest available version is downloaded from the repository and placed in a folder node_modules. In this case, the corresponding records are added to the files package.jsonand package-lock.jsonlocated in the project folder.

In addition, by installing a package, npm finds and installs its dependencies.

Suppose we install the cowsay package already familiar to you by executing the command npm install cowsay. The package will be installed in the node_modulesproject folder , and the package.jsonfollowing entry will be in the file :

{
  "dependencies": {
    "cowsay": "^1.3.1"
  }
}

In the package-lock.jsonsame information will be made about this package. Here is his fragment:

{
  "requires": true,
  "lockfileVersion": 1,
  "dependencies": {
    "cowsay": {
      "version": "1.3.1",
      "resolved": "https://registry.npmjs.org/cowsay/-/cowsay-1.3.1.tgz",
      "integrity": "sha512-3PVFe6FePVtPj1HTeLin9v8WyLl+VmM1l1H/5P+BTTDkMAjufp+0F9eLjzRnOHzVAYeIYFF5po5NjRrgefnRMQ==",
      "requires": {
        "get-stdin": "^5.0.1",
        "optimist": "~0.6.1",
        "string-width": "~2.1.1",
        "strip-eof": "^1.0.0"
      }
    }
  }
}

From these two files, you can see that we installed cowsay version 1.3.1, and that the package update rule is specified as ^1.3.1. In the fourth part of this series of materials we have already talked about the rules of semantic versioning. Recall that such a record means that npm can update the package when its minor and patch versions are released.

If, for example, a new minor version of a package comes out and we execute the command npm update, the installed version of the package is updated and the information about the installed package is updated in the file package-lock.json, and the file package.jsonremains unchanged.

In order to find out whether new versions of packages used in the project have been released, you can use the following command:

npm outdated

Here are the results of executing this command for a project whose dependencies have not been updated for a long time:


Analysis of obsolete project dependencies.

Some of the available package updates are their major releases, updates to which will not occur when the command is executednpm update. Upgrading to major releases is not done by this team, since they (by definition) can contain serious changes that are not backward compatible with previous major releases, and npm seeks to save the developer from the problems that can cause the use of such packages.

To upgrade to major new versions of all used packages, globally install the packagenpm-check-updates:

npm install -g npm-check-updates

Then run the utility provided by it:

ncu -u

This command will update the file package.json, making changes to the instructions for suitable versions of packages in the dependenciesand sections devDependencies. This will allow npm to upgrade the packages used in the project to new major versions after running the command npm update.

If you want to install the latest version of the packages for the newly just downloaded project, which does not yet have a folder node_modules, then, instead npm update, run the command npm install.

Local or global package uninstallation


To uninstall a package that was previously installed locally (using the command install <package-name>), run a command like this:

npm uninstall <package-name>

If the package is installed globally, then you will need to use the flag to remove it -g(--global. For example, a similar command might look like this:

npm uninstall -g webpack

When executing such a command, the current folder does not matter.

About the choice between global and local installation of packages


When and why packages are best to install globally? In order to answer this question, let us recall the differences between local and global installation of packages:

  • Local packages are installed in the directory in which the command is executed npm install <package-name>. Such packages are located in a folder node_moduleslocated in this directory.
  • Global packages are installed in a special folder (in which exactly - depending on the specific settings of your system), regardless of where exactly the command is executed npm install -g <package-name>.

Connection of local and global packages in the code is the same:

require('package-name')

So what is the best way to install packages?

In general, all packages should be installed locally. Thanks to this, even if you have dozens of Node.js projects, you can ensure, if necessary, that they use different versions of the same packages.

Updating the global package leads to the fact that all projects in which it is used will use its new release. It is easy to understand that this, in terms of supporting projects, can lead to a real nightmare, since new releases of some packages may turn out to be incompatible with their old versions.

If each project has its own local version of a certain package, even though this may seem like a waste of resources, this is a very small fee for avoiding the negative consequences that may be caused by the incompatibility of new versions of packages being updated centrally with the project code.

Packages should be installed globally if they are some command line utilities that are used in many projects.

Similar packages can be installed locally by running the command-line utilities they provide using npx, but some packages are still better to install globally. Such packages that you may well know are, for example, the following:

  • npm
  • create-react-app
  • vue-cli
  • grunt-cli
  • mocha
  • react-native-cli
  • gatsby-cli
  • forever
  • nodemon

It is possible that your system already has packages installed globally. To find out about it, use the following command:

npm list -g --depth 0

About project dependencies


When should a package be considered as a normal project dependency, necessary for its operation, and when - how is the development dependency?

When installing a package using a view command, npm install <package-name>it is installed as a regular dependency. An entry for such a packet is made in the dependenciesfile section package.json(until the release of npm 5, such an entry was made only when using the flag --save, now it is not necessary to use it for this).

Using the flag --save-devallows you to set the package as a development dependency. A record of it is made in the devDependenciesfile section package.json.

Development dependencies are packages that are needed during the project development process; in the course of its normal operation, they are not required. Such packages include, for example, testing tools, Webpack, Babel.

When a project is deployed using a command npm installin its folder, in which there is a folder containing the file package.json, this will result in the installation of all dependencies, since npm assumes that a similar installation is being performed for the purposes of working on the project.

Therefore, if the package needs to be deployed in production, then when it is deployed, you need to use the npm command install --production. Thanks to the flag, --productiondependencies of development will not be installed.

Npx utility


Now we will talk about one very powerful team, npx , which appeared in npm 5.2. One of its features is the launch of executable files included in the npm-packages. We have already considered using npx to run a similar file from the cowsay package. Now let's talk about this in more detail.

▍Using npx to simplify running local commands


Node.js developers published many executable files (utilities) in the form of packages that were supposed to be installed globally, which provided convenient access to their capabilities, since they could be run from the command line simply by typing the name of the corresponding command. However, working in such an environment was very uncomfortable in the event that it was necessary to install different versions of the same packages.

Using the view command npx commandnameautomatically searches for the desired file in the project folder node_modules. This eliminates the need to know the exact path to such a file. It also makes it unnecessary to globally install a package and ensure access to it from anywhere in the file system through the use of a system variable PATH.

▍ Execution of utilities without the need to install them


In npx there is another interesting feature, thanks to which utilities can be launched without prior installation. This is mainly useful for the following reasons:

  • No utility installation required.
  • You can run different versions of the same utilities, indicating the desired version using the design @version.

Let's look at how to use this mechanism, using the example of a utility you already know cowsay. So, if the cowsay package is installed globally, executing the command line command cowsay "Hello"will output a “talking cow” to the console:

_______
< Hello >
 -------
        \  ^__^
         \ (oo)\_______
            (__)\      )\/\                ||----w |
                ||     ||

If the cowsay package is not installed globally, a similar command will generate an error.

The npx utility allows you to run such commands without installing them. In our example, this looks like this:

npx cowsay "Hello"

Such a team will work, but, although the “talking” cow, by and large, does not bring any special benefit, the same approach can be used to carry out much more useful commands. Here are some examples:

  • There is a command line tool designed to create and run Vue applications. Using npx it can be called as follows: npx vue create my-vue-app.
  • To create React-applications, you can use the utility create-react-app. Her call through npx looks like this: npx create-react-app my-react-app.

After downloading and using the appropriate npx code, it will be deleted.

▍ Run JavaScript code using different versions of Node.js


In order to run some code using different versions of Node.js, you can, using npx, refer to the npm-package node, indicating its version. It looks like this:

npx node@6 -v #v6.14.3
npx node@8 -v #v8.11.3

This eliminates the need for tools like nvm or other Node.js version managers.

▍ Running arbitrary code fragments available at a certain address


Npx allows you to run not only the code published in npm. In particular, if you have a link to a certain fragment of code (say, published on GitHub gist), you can start it like this:

npx https://gist.github.com/zkat/4bc19503fe9e9309e2bfaa2c58074d32

Of course, when executing such a code, one should not forget about security. Npx gives the developer a lot of opportunities, but they also mean more responsibility.

Т Results


Today we talked about some useful npm mechanisms and about using npx. At this stage, you should have a basic understanding of the npm device and methods of working with this package manager. If you want to learn more about npm, refer to the project documentation page and experiment more.

Next time we will discuss some of the basic Node.js mechanisms, which need to be understood in order to successfully develop applications for this platform.

Dear readers! Do you use npx?


Also popular now: