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 /home/username/example.com └── firstname.lastname@example.org npm WARN enoent ENOENT: no such file or directory, open '/home/username/example.com/package.json' npm WARN example.com No description npm WARN example.com No repository field. npm WARN example.com No README data npm WARN example.com 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 lodash
Testing your locally installed package
This example is taken from docs.npmjs.com.
Create a file named index.js, with the following code:
// index.js var lodash = require('lodash'); var output = lodash.without([1, 2, 3], 1); console.log(output);
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: /example.com/package.json Locally installed package package.json file: /example.com/node_modules/<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 /home/username/.nvm/versions/node/v12.14.0/lib └── email@example.com