JavaScript

Managing Node.js Packages

There are many different modules available for Node.js.Some, like the http package already briefly shown, are included in the installation of Node.js; others can be installed later via the Node.js Package Manager (NPM).

 

Installing the Node.js Package Manager

You have several options to install the NPM tool: MSI and .pkg installation files are available for Windows and Mac, and a corresponding installation script is available for Unix systems. Further installation options are described in detail at https://github.com/npm/npm.

 

However, much more common than a separate installation of NPM is indirect installation via Node.js. Since version 0.6.3, NPM is already included in the installation of Node.js. As already described, the latter can be downloaded from http://nodejs.org/download/ as an installation or executable file for the various operating systems. After installing Node.js, NPM is also directly available to you as the npm command line command. You can verify the installation by running the npm --version command, which outputs the version number of the installed NPM.

 

Version Numbers of NPM and Node.js: The version number of NPM is not identical to the version number of Node.js. Currently, for example, the node --version command on my computer outputs version 16.2.0, while the npm --version command outputs version 7.13.0.

 

Installing Packages

With NPM, you can install packages either locally or globally. The former is useful if you want to install a particular Node.js package as a dependency of one of your applications, while the latter makes sense in cases where you want a Node.js package to be globally available to all of your applications, or if it's a tool like mocha or Grunt that you want to be globally available.

Installing Packages Locally

The command for installing a package is npm install <package> (or in short form: npm i <package>), where <package> stands for the package to be installed. For example, to install the lodash package (https://lodash.com/), you call the following command: npm install lodash (or npm i lodash).

 

Then NPM creates a new directory named node_modules in the current directory if there is no such directory already and installs the lodash package into this directory.

 

NPM not only ensures that the package specified is installed, but also, as mentioned, that all dependencies of the package are installed. This is done recursively for each package to be installed until all dependencies have been resolved and installed as well.

 

Strictly speaking, you can use not only the name of a package for <package>, but also, for example, URLs, such as those pointing to a GitHub repository. You can find an overview of the various package installation options at https://docs.npmjs.com/cli/install.

Installing a Package with a Specific Version

By default, NPM installs the last current version of a package. But if you want to install a specific version of a package, simply specify it after the name of the package—for example, npm install lodash@4.3.5.

Installing Packages Globally

To install a package globally, the -g (or --global) flag must be passed as an argument to the install command. Because, depending on the configuration, the global packages are located in a directory for which you only have write access with administrator permissions, in such cases the command should be executed under the appropriate identifier. In Unix-based environments, for example, you would execute sudo npm install -g <package>.

 

Updating NPM: Because NPM usually is updated more frequently than Node.js, you can also update NPM separately. Conveniently, this can be done via NPM itself by running the sudo npm install -g npm command, because NPM itself is also an NPM package.

Overview of Various Web APIs

If you enter the name of a package for <package>, it must be registered in the NPM registry, a directory for available packages. NPM obtains all packages from the registry at http://registry.npmjs.org by default. In principle, however, a customized registry can also be hosted on its own server. For an overview of the packages available in the default registry, see www.npmjs.org. Currently, over a million packages are listed there (as of May 2021). For comparison: There were about 475,000 packages in October 2017, 250,000 in May 2016, and 95,000 in September 2014.

 

A small selection of known packages is shown in this table.

 

Using Packages

 

As mentioned, Node.js and thus NPM follow the CommonJS module format. This means that to use a package, you must include or import it via require().

 

An example is shown in the listing below. The lodash package you just installed is integrated via require('lodash') and assigned to the _ variable. This variable subsequently contains references to all functions and objects exported by the lodash package. One of these functions is the includes() function, which checks an array to see if it contains a particular value, and is applied to the names array in the example.

 

const _ = require('lodash');

const names = ['John', 'James'];

console.log(_.includes(names, 'James')); // Output: true

 

Creating Your Own Packages

Of course, it’s also possible to create your own packages for Node.js. To do this, you can use the npm init command, which guides you through the steps using a command line wizard. The information highlighted in the next listing is queried consecutively. The result of the wizard is a file named package.json (the package configuration file), the contents of which can be seen at the end of the listing.

 

This utility will walk you through creating a package.json file.

It only covers the most common items, and tries to guess sane defaults.

 

See `npm help json` for definitive documentation on these fields

and exactly what they do.

 

Use `npm install <pkg> --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: (package) sample package

version: (0.0.0) 1.0.0

description: Sample package JavaScript manual

entry point: (main.js)

test command: mocha

git repository:

keywords: javascript

author: Philip Ackermann

license: (ISC) MIT

About to write to /Users/philipackermann/Documents/Arbeit/Rheinwerk/

JavaScriptHandbuch/Quelltext/Kapitel17/package/package.json:

 

{

   "name": "sample package",

   "version": "1.0.0",

   "description": "Sample package JavaScript Manual,

   "main": "main.js",

   "scripts": {

      "test": "mocha"

   },

 

   "keywords": [

      "javascript"

   ],

   "author": "Philip Ackermann",

   "license": "MIT"

}

 

Is this ok? (yes)

 

This configuration file is a JSON file that contains various pieces of information about a package. The file must be present in each package and must contain at least the name and version number of the respective package; otherwise, it can’t be installed. The combination of name and version number uniquely identifies a package. Both are required by NPM to resolve and download dependencies.

 

Dependencies of a Package: In addition to general data about the package, the dependencies to other packages are also defined in the configuration file. If you install a package via NPM, the dependencies are installed directly from this file in the correct version if necessary.

 

The JSON format used is loosely based on the package descriptor file format defined under CommonJS (http://wiki.commonjs.org/wiki/Packages/1.0#Package_Descriptor_File). The table below provides an overview of the most important properties that can be used in this context. For a complete list, visit https://docs.npmjs.com/files/package.json.

 

The Various Properties of the package.json Configuration File

 

Get Information about Packages: You can use the npm info <package> command to output the package.json file of the corresponding package without the package having to be installed on your computer. NPM retrieves the information from the NPM registry and outputs the file on the console. This can be handy if you want to check certain prerequisites before installing a package—for example, dependencies used, support of a certain operating system, and so on.

 

Adding Dependencies to the package.json File: By specifying the additional --save parameter in the npm install command, the dependency is not only downloaded, but also directly marked as a dependency in the package.json file:

 

npm install lodash –save

 

The --save-dev parameter analogously writes the dependency to the development dependencies (devDependencies) of the configuration file:

 

npm install mocha --save-dev

 

After executing the preceding commands, the package.json file from just now would look as shown here.

 

{

   "name": "sample package",

   "version": "1.0.0",

   "description": "Sample package JavaScript Manual",

   "main": "index.js",

   "scripts": {

      "test": "mocha"

   },

   "keywords": [

      "javascript"

   ],

   "author": "Philip Ackermann",

   "license": "MIT",

   "dependencies": {

      "lodash": "~4.17.21",

   },

   "devDependencies": {

      "mocha": "~8.4.0"

   }

}

 

Editor’s note: This post has been adapted from a section of the book JavaScript: The Comprehensive Guide by Philip Ackermann.

Recommendation

2286-Jan-04-2023-04-33-57-2595-PM-1-1-1-1-1-1-1
JavaScript

Begin your JavaScript journey with this comprehensive, hands-on guide. You’ll learn everything there is to know about professional JavaScript programming, from core language concepts to essential client-side tasks. Build dynamic web applications with step-by-step instructions and expand your knowledge by exploring server-side development and mobile development. Work with advanced language features, write clean and efficient code, and much more!

Learn More
Rheinwerk Computing
by Rheinwerk Computing

Rheinwerk Computing is an imprint of Rheinwerk Publishing and publishes books by leading experts in the fields of programming, administration, security, analytics, and more.

Comments