Welcome to ciysys blog

Install Node.js and PM2

Published on: 5th Dec 2020

Updated on: 15th Oct 2023

What is Node.js

Node.js is a virtual machine for hosting JavaScript programs. It is powerful such that you can write a simple website in a few lines of code.

Why we need it

You may develop your website using Node.js or develop a script to analyze the web access log, etc.

Here's how you install Node.js

There are two ways to install Node.js

  1. To use nvm in managing Node.js version,

    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash
    source ~/.bashrc
    

    To view the latest version (please choose LTS - Long Term Support version),

    nvm list-remote
    
    nvm install v18.16.0
    nvm use v18.16.0
    

    Notes: nvm is not the only version manager. There is another one called n which will be explained below.

  2. To install Node.js directly.

    cd ~
    
    # download the setup script - you may review it before executing this script
    curl -sL https://deb.nodesource.com/setup_16.x -o nodesource_setup.sh
    
    sudo bash nodesource_setup.sh
    sudo apt install nodejs
    sudo apt install build-essential
    

Maintaining Node.js app dependencies

First, you have to set the current location to the same as the package.json of your app.

cd /var/www/app1

Install PM2

The website hosted in Node.js will not be back online after server reboot. In this case, we need a program to start the website. There are many options to achieve this. For us, we choose pm2 due to its flexibility and easy to configure.

Adding Node.js app to pm2 using ecosystem.config.js file

Schedule a task

Troubleshooting

Error: "/usr/bin/env node: No such file of directory"

Updated on: 15.Oct.2023

If you are using nvm node version manager, use this comment to create a symlink:

sudo ln -s "$(which node)" /usr/bin/node

Error: "current user does not have permission to access the dev dir /root/.cache/node-gyp/xxx"

Updated on: 15.Oct.2023

When you run npm install better-sqlite3 and the following error returned,

prebuild-install warn install EACCES: permission denied, access '/root/.npm'
gyp WARN EACCES current user ("helomiao") does not have permission to access the dev dir "/root/.cache/node-gyp/18.16.0"
gyp WARN EACCES attempting to reinstall using temporary dev dir "/var/www/app-ciysys-com/demoapp/node_modules/better-sqlite3/.node-gyp"

Try to add --unsafe-perm to install the package,

npm install better-sqlite3 --unsafe-perm

References

Related posts

Jump to #UBUNTU blog

Author

Lau Hon Wan, software developer.