Node.js — installing packages

Installing Node.js and npm

To ensure compatibility with Node.js packages, it's always recommended that you install a custom version of Node.js under your username, rather than using the default server version. Use the following article to install a custom version of Node.js:

Once installed, npm is also installed and you'll be able to run the commands below.

Local package installation

It's only recommended that you install packages locally for each individual project.

To install a package locally, navigate to your site's application directory (not the /public directory). The command to install a package is:

[server]$ npm install <package_name>

For example, this installs a packages called 'lodash'.:

[server]$ npm install lodash
└── lodash@4.17.4

npm WARN enoent ENOENT: no such file or directory, open '/home/username/'
npm WARN No description
npm WARN No repository field.
npm WARN No README data
npm WARN No license field.

This creates a directory in your site's application directory called /node_modules.

You should then check to confirm it was correctly installed. You must be in your site's application directory where the local /node_modules directory resides:

[server]$ ls node_modules

Testing your locally installed package

This example is taken from

Create a file named index.js, with the following code:

// index.js 
var lodash = require('lodash');
var output = lodash.without([1, 2, 3], 1);

Run the file using node index.js. It should output [2, 3].

[server]$ node index.js
[ 2, 3 ]

If the module was not correctly installed, an error would be thrown.

Creating a packages.json file for locally installed packages

It's a good idea to create a local packages.json file in your site's application directory where the /node_modules directory resides. This package.json file helps to manage your locally installed packages.

To be clear, this package.json file is different than the package.json file within any locally installed package. For example:

Local site package.json file location: /
Locally installed package package.json file: /<module_name>/package.json

Global package installation

If your project depends on a specific package, it should always be installed locally as shown above. Global installs should be reserved for packages that your projects do not depend on, such as CLI utilities. 

Use the -g flag to install a package globally:

[server]$ npm install -g <package_name>

You can confirm which packages are installed globally by running the following:

[server]$ npm list -g --depth=0
└── npm@6.13.4

See also

Did this article answer your questions?

Article last updated PST.