Node.js is an open-source platform runtime environment for running Javascript on the server. This guide will take you through installing the latest version of Node.js across many Linux distributions. We’ll focus primarily on Ubuntu VPS, but we’ll also include commands for Almalinux, Rocky Linux, and Fedora.
1. Learn why Node.js is important for scalable, server-side JavaScript apps.
Node.js is a powerful, open-source JavaScript runtime environment used for building server-side applications on Linux and other platforms. Unlike traditional JavaScript, which only runs in the browser, Node.js allows JavaScript code to execute on the server. This shift enables developers to use JavaScript for both frontend and backend development, creating a seamless, unified codebase for full-stack applications. A major benefit of Node.js is its nonblocking event-driven nature that enables us to handle many concurrent operations very easily on the Node.js event loop; typical use cases for this would be things like Chat Apps, Online games, Collaboration tools, etc.
Node.js is built on the V8 JavaScript engine, known for its high performance and support for modern JavaScript features. It also includes npm (Node Package Manager), a vast library of pre-built modules and packages, which helps in development by providing reusable code for many functionalities. By combining speed, scalability, and extensive libraries, Node.js has become an important tool in modern web development.
Node.js has reshaped web development by enabling JavaScript to be used on the server side. Full-stack application development is possible with a single language to simplify the development and have real-time, data-intensive applications. Well known for its event-driven, nonblocking I/O model that is great for scalable network applications, Node.js is also very popular.
2. Update Node.js for better performance, security, and new features.
Using the latest version of Node.js, whether on Ubuntu or other distributions, brings many benefits.
- Performance Gains: Each new release optimizes performance for better speed.
- Security Updates: New versions include patches to fix vulnerabilities.
- Feature Improvements: Updated versions provide access to the newest JavaScript features and Node.js APIs.
- Community Support: Check for compatibility with popular packages and libraries.
3. Check important requirements before installing Node.js.
Check the following before proceeding:
- User Access: Root or sudo user permissions.
- Internet Connection: Required for downloading packages.
- Command Line Knowledge: Basic familiarity helps.
Package Manager Update:
sudo apt update # For Ubuntu
sudo dnf update # For Fedora, Almalinux, Rocky Linux
4. Install Node.js on Ubuntu using NodeSource PPA, making sure you have the latest features and support.
Ubuntu’s flexibility and ease of use make it a popular choice for server environments. Below, we outline two primary methods for installing Node.js on Ubuntu.
4.1 Using NodeSource PPA in NodeJS
There is a NodeSource repository that makes it easier to install the latest version of Node.js.
Steps:
Update your system and install prerequisites:
sudo apt update
sudo apt install curl software-properties-common
- Add the NodeSource repository in NodeJS:
NodeSource provides a comprehensive range of Node.js versions to meet varied project and development needs. Here’s a detailed breakdown:
- Current Versions: Node.js 23.x comes with the latest features and enhancements, ready for developers to explore the newest features and experiment with the latest.
- Recent Releases: Versions like 22.x and 21.x offer improvements over LTS but may be less widely adopted for production.
- Long-Term Support (LTS) Versions: They are — 20.x, 18.x, and 16.x, which are recommended in terms of production use as they have been stable, have a consistent update period, and extended support period.
- Older LTS Releases: Versions such as 14.x and 12.x continue to support older applications that haven’t migrated to newer versions but still require a reliable and supported runtime.
- Legacy Versions: Releases like 10.x are used in maintaining compatibility for legacy systems and applications where updates might not be feasible.
curl -fsSL https://deb.nodesource.com/setup_23.x | sudo -E bash -
Replace 23.x with your desired version (e.g., 20.x).
Adding on to the step where you are adding the NodeSource repository is adding an external repository that will directly provide you with the latest versions of Node.js through your package manager. The reason for this step is so you can skip the long wait that is the default typically slower system repository updates and provide you with the most up-to-date versions of Node.js. To proceed, use the provided curl command to add the repository, which downloads and runs a script to configure the repository settings. By completing this step, you enable apt, dnf, or similar tools to recognize the NodeSource repository and its available packages, preparing the system for Node.js installation.
How to Add NodeSource for Specific Node.js Versions
Adding the NodeSource repository makes sure you have access to specific Node.js versions directly on your Linux system, bypassing default repositories that may not be up-to-date. Each command uses curl to securely download the NodeSource setup script for a particular Node.js version. The | sudo -E bash – part executes the script with sudo, adding the repository to your package manager.
Commands for Adding NodeSource Repositories:
- Version 23 (Latest):
curl -fsSL https://deb.nodesource.com/setup_23.x | sudo -E bash -
- Version 22:
curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
- Version 21:
curl -fsSL https://deb.nodesource.com/setup_21.x | sudo -E bash -
- Version 20 (LTS):
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
- Version 19:
curl -fsSL https://deb.nodesource.com/setup_19.x | sudo -E bash -
- Version 18 (LTS):
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
- Version 17:
curl -fsSL https://deb.nodesource.com/setup_17.x | sudo -E bash -
- Version 16 (LTS):
curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
- Version 15:
curl -fsSL https://deb.nodesource.com/setup_15.x | sudo -E bash -
- Version 14 (LTS):
curl -fsSL https://deb.nodesource.com/setup_14.x | sudo -E bash -
- Version 13:
curl -fsSL https://deb.nodesource.com/setup_13.x | sudo -E bash -
- Version 12 (LTS):
curl -fsSL https://deb.nodesource.com/setup_12.x | sudo -E bash -
- Version 10 (Older LTS):
curl -fsSL https://deb.nodesource.com/setup_10.x | sudo -E bash -
- Install Node.js:
sudo apt install nodejs
The command sudo apt install nodejs is used to install Node.js and its dependencies directly from the repository configured earlier. Running this command will download and install Node.js along with npm (Node Package Manager), which is important for managing Node packages and dependencies for your projects. Node.js can be used system-wide with this installation method, which is simple and very quick for setting up a Node.js environment. You will then install; once that is done, you can verify with node -v to check the Node js version and npm -v to see the npm version to confirm everything is up and set for development.
- Verify installation of NodeJS:
node -v
Confirmation of the installation is important after installing Node.js and npm because your development environment is ready. If you do not have node -v that tells you the installed version of Node.js, you need to set up the runtime properly, or it is broken. Next, check npm -v to view the npm version, as it comes bundled with Node.js and is important for managing project dependencies. This step helps confirm that npm is correctly linked to the Node.js installation. These simple verification commands provide confidence that the installation was completed without errors, allowing you to proceed with building and managing Node.js projects.
npm -v
4.2 Manage multiple Node.js versions on Ubuntu and Linux environments seamlessly with NVM for more flexibility.
NVM simplifies the management of multiple Node.js versions on the same system. It is particularly useful to developers working on projects that need different versions of Node.js for separate parts of their work. Just run the curl command provided to install the latest NVM installation script from its GitHub repository. After you install NVM, add a source to .bashrc or .zshrc, so NVM is ready on your shell right away. Install different versions of Node.js smoothly with NVM, change between different versions easily, and set up a default version. This functionality enables you to test applications with various Node.js versions, ensuring compatibility across different projects.
Steps:
Installing NVM with NodeJS:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash
- Activate NVM in NodeJS:
Once NVM is installed, it must be activated to be usable in your current shell session. Activation makes sure that NVM commands and Node.js version management are available immediately. To activate NVM, use the command source ~/.bashrc or source ~/.zshrc, depending on the shell you are using. This command reloads your shell configuration file, which applies any changes made during the NVM installation. If you’re using a different shell, such as fish or csh, Make sure you source the appropriate configuration file. This step is important to start using NVM without needing to log out and back in or open a new terminal window.
source ~/.bashrc
- Install the latest version of Node.js:
nvm install node
With NVM activated, installing the latest version of Node.js becomes simple. Run the command nvm install node to download and install the Node.js. This command instructs NVM to fetch the latest available version directly from the Node.js repository and install it on your system. The benefit of using NVM is that it isolates the Node.js versions, preventing conflicts between projects that may require different versions. Once installed, this version becomes immediately usable, allowing you to start developing or running your Node.js applications without further setup.
- Set the default version in NodeJS:
nvm alias default node
After installing multiple versions of Node.js using NVM, setting a default version confirms that a specific version is automatically used whenever you open a new terminal session. To configure the default version, execute the command: nvm alias default node, where node refers to the latest version installed. If you wish to set a specific version, replace the node with the version number (e.g., nvm alias default 18.20.4). This command helps maintain consistency across projects and workflows, making sure that you always start with the version you need by default without manually switching each time.
- Verify installation of NodeJS with version:
node -v
Verifying your Node.js installation confirms that everything is properly configured and ready for use. Start by running node -v to check the Node.js version installed. This command should return the version number, confirming that Node.js has been correctly set up on your system.
Verify version of NodeJS:
npm -v
Next, verify the npm installation by running npm -v, which displays the npm version linked with your Node.js installation. This check is important because npm is used for managing packages and dependencies in your projects. If both commands return valid version numbers, your installation is complete, and your development environment is ready for Node.js application development.
5. Installing Node.js on Alma Linux, Rocky Linux, Fedora
These RHEL-compatible distributions use the dnf package manager for installations.
Steps:
Update your system:
sudo dnf update
- Add NodeSource repository:
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
- Install Node.js:
sudo dnf install nodejs
- Verify installation:
node -v
npm -v
6. Learn how to manage Node.js versions on Ubuntu and other Linux systems using NVM, making it easy to install, switch, and set default versions.
Managing different versions is important for projects requiring specific Node.js versions.
Using NVM in NodeJS:
List installed versions in NodeJS:
nvm list
Having different version dependencies is an important reason why you should manage multiple versions of Node.js. nvm list helps keep your track of all versions you have installed on your system. This command gives a grand tour of all Node.js versions available along with an arrow (->) pointing to the current one. But it also shows aliases such as default, system, or stable if configured. This command will tell you what versions are suitable for you to use because it is quick and easy to spot when it’s time to change a version for a particular project. In this step, we have ensured a smooth workflow on many development needs.
- Install a specific version of NodeJS:
nvm install 14.20.1
To install a Node.js version, you need to run nvm install; for example, nvm install 14.20.1. This process retrieves the chosen version directly from the official Node.js repository. The NVM side benefit is that installations are isolated to prevent any system-wide conflict. This flexibility is good when you have projects and you either have to or want to run them on a specific Node.js version for timekeeping reasons. Once it’s installed you can change which version you are using with nvm use. This approach keeps your many development projects safe and in compliance, so you don’t have to worry about problems later.
- Switch to a version in NodeJS:
nvm use 16
Switching Node.js versions is important for developers who work on projects that require different Node.js environments. With NVM, you can easily change versions by running nvm use <version> (e.g., nvm use 16). This command switches your active Node.js version to the specified version, enabling compatibility with the project requirements. The active version remains in use until you close the terminal or run another nvm use command. This feature is very useful for testing your code under many Node.js releases to identify potential issues or performance differences, streamlining multi-version development workflows.
- Set a default version of NodeJS:
nvm alias default 14
This setup ensures that a default Node.js version is configured whenever you start a new terminal session. You can do this by setting up nvm alias default (e.g., nvm alias default 14) to configure this. This command makes your workflow easier to handle by removing the need to switch versions each time manually. This technique is really great for developers who generally work on a fundamental job utilizing a particular Node.js variant. Having a default helps you maintain consistency with what’s in your session and what’s in your development environment, and when you start coding, that saves you from potential version conflicts.
7. Verify Production Stability with Node.js and PM2: A Complete Guide
PM2 is an important tool for Node.js developers looking to manage their applications in production. It provides robust features for running applications seamlessly, enhancing reliability, and improving operational management.
1. What is PM2 in NodeJS?
PM2 is a powerful process manager for Node.js applications that runs apps in the background, manages their lifecycle, and provides high availability through automatic restarts.
2. Benefits of Using PM2 with NodeJS:
- Automatic Restarts: Keeps your app running even after unexpected crashes.
- Monitoring: Tracks memory usage and CPU performance for optimization.
- Load Balancing: Easily scales your app across multiple CPU cores.
- Auto-Start on Reboot: Configures your server to restart apps automatically after a reboot.
- Advanced Logging: Provides detailed logs for better debugging and maintenance.
3. How to Install PM2 in NodeJS:
Install PM2 globally on your system with the following command:
npm install -g pm2
4. Running Your Node.js App with PM2:
To start your Node.js application with PM2, run:
pm2 start app.js
This command will start app.js as a background process, and PM2 will monitor it, automatically restarting it in case of a crash.
5. Monitor Your Application in NodeJS with pm2:
PM2 includes monitoring tools that provide valuable information about your running applications:
View Process List of pm2 NodeJS:
pm2 list
- Detailed Metrics in pm2:
pm2 monit
6. Configure Auto-Restart of NodeJS on Server Reboot using pm2:
Make sure your application restarts automatically after a server reboot:
Run the following command to generate and configure the startup script:
pm2 startup
- Follow the instructions to complete the setup.
Save the current process list for automatic startup:
pm2 save
7. Managing Multiple Applications using pm2 on NodeJS:
PM2 makes it easy to scale your application across all available CPU cores:
pm2 start app.js -i max
The -i max option runs your app in cluster mode, optimizing performance by utilizing all CPU cores.
To increase the memory allocation limit for Node.js beyond the default 1GB, you can use the –max-old-space-size flag when running your Node.js application. This flag tells Node.js to allocate a specific amount of memory (in megabytes) for the V8 JavaScript engine. Here’s how to do it using PM2:
8. Command to Run Node.js with More Memory Using PM2
If you want to allocate, for example, 8GB of memory to your Node.js application, you can run:
pm2 start app.js --node-args="--max-old-space-size=8192"
Explanation:
- –node-args=”–max-old-space-size=8192″: This argument passes the memory allocation flag to Node.js, where 8192 represents 8GB in megabytes. This value can be modified to suit your specific requirements (e.g., 4096 for 4GB, 2048 for 2GB, etc.).
- PM2: Manages your application processes, making it easy to monitor and manage resource allocation.
Why This Tip Is Useful:
Some options have additional features that have memory requirements, for example, ones that are applied to large data sets or run long-running, intensive computations. This command will let you specify the resources required to run at its best without running into memory limits.
9. Quick Steps to Adjust Memory Limit in NodeJS for pm2:
Install PM2 (if not already installed) in NodeJS:
npm install -g pm2
- Run the app with increased memory:
pm2 start app.js --node-args="--max-old-space-size=8192"
- Bonus Tip:
To distribute your application workload across multiple CPU cores with more memory, combine this with the cluster mode:
pm2 start app.js -i max --node-args="--max-old-space-size=8192"
- -i max: Runs your app in cluster mode, using all available CPU cores.
This setup makes sure your application runs with more memory distributed across all CPU cores for optimized performance in a production environment.
8. Run simple tests to confirm your Node.js installation.
Make sure your Node.js installation is real, and a good thing to verify that you are all set up right and are running right. It is a step that helps us by verifying that everything is working as it should and the Node.js instance is ready for use when working on projects in your development area.
Steps to Verify Installation of NodeJS:
Creating a test script is a simple way to check your Node.js installation is functional. Begin by opening your terminal and creating a new JavaScript file using a Text editor like Nano or Vim:
nano test.js
In the file, add a simple line of code that outputs a message to confirm Node.js is running:
console.log("Node.js is successfully installed!");
This code uses the console.log() function to print a message to the terminal, verifying that Node.js can execute JavaScript code properly. After adding this line, save and Exit the editor (CTRL + X, then Y, and press Enter).
- Run the script:
Once your test.js file is created with the verification code, it’s time to run it to confirm that Node.js is functioning correctly. Navigate to the directory containing test.js (if you aren’t already there) and execute the script with the following command:
node test.js
This command tells Node.js to interpret and run the JavaScript code in test.js. If everything is installed correctly, the output should appear in your terminal as:
Node.js is successfully installed!
9. Improve Node.js development on Linux with top tools and tips.
- Use a modern code editor:
Having the right code editor can have a greatly positive impact on your development workflow. From a quick search, it seems like Visual Studio Code (VS Code) is a highly recommended option for the development of node.js because it has very advanced features as well as a large extension support. With syntax highlighting, IntelliSense for smart code completion, Git integration built in, and a powerful debugger for JavaScript and Node.js, VS Code is the favorite among thousands of developers around the world. In addition, it enables you to install extensions, like Node.js Essentials that are the extensions which will help you deliver the Node.js project error-free and save valuable time with additional Node.js support.
Install nodemon for live reloading:
nodemon is a useful tool for Node.js development that automatically restarts your application whenever file changes are detected, streamlining your workflow. This tool is very valuable for local development, as it eliminates the need to restart your server after each update manually.
npm install -g nodemon
- Monitor global packages of NodeJS:
Managing your development environment relies on keeping track of the globally installed npm packages. They can be important development tools such as nodemon, pm2, or typescript and are just global packages. They are the ones to monitor to prevent version conflicts between different projects and for consistency as a whole.
To list all globally installed npm packages, use:
npm list -g --depth=0
Any command that shows a concise list of your global packages and their installed versions. The –depth=0 option ensures we don’t display nested dependencies, just showing top-level dependencies. Checking this list on a regular basis will tell you which packages aren’t needed anymore and which ones are outdated and can be updated, keeping your environment clean and up to date.
- Use LTS versions in NodeJS:
When working on Node.js projects, it is generally best practice to use LTS (Long-Term Support) versions. These versions are maintained for a longer period and receive updates that focus on stability, security, and important bug fixes, making them a reliable choice for most applications. LTS versions make sure of compatibility with the broader Node.js ecosystem, including popular packages and frameworks that prioritise support for these versions.
nvm install --lts
10. Quickly resolve common Node.js and NVM installation issues on Ubuntu and other Linux systems
Error: nvm: command not found
If the error ‘nvm: command not found’ appears, it typically means that the NVM installation path still needs to be added to your shell’s configuration file. This issue prevents the terminal from recognizing NVM commands. To fix this, you’ll need to add the NVM initialization script to your shell configuration file.
Add this to ~/.bashrc or ~/.zshrc:
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
- NPM permission issues
NPM permission issues can arise when you try to install global packages and face errors related to access rights. This problem often arises when npm attempts to write to directories that require root permissions. To solve this without using sudo, you can configure npm to use a directory within your user space.
Create a global directory:
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
export PATH=~/.npm-global/bin:$PATH
- Dependencies not found
Sometimes, when installing packages or running Node.js applications, you may face errors related to missing dependencies. This issue can arise when required system libraries or build tools need to be installed. To address this, you need to install development tools that provide the necessary components.
Install build tools:
sudo apt install build-essential # Ubuntu
sudo dnf groupinstall "Development Tools" # Fedora
11. Additional Resources for Learning Node.js
- Node.js Official Documentation: nodejs.org
- MDN Web Docs: Comprehensive JavaScript and Node.js guide developer.mozilla.org
- Stack Overflow: Community Q&A for solving Node.js issue stackoverflow.com
- Reddit: A Community for solving Node.js issues Reddit
- Prerequisites: Check if your system meets these prerequisites before Node.js installation. Visit the Node.js installation guide.
- Managing Node.js Versions: Learn to install, switch, and set default Node.js versions for project-specific needs.
- Tips for Node.js Development: Boost your productivity with the right tools, like VS Code and nodemon.
12. Conclusion
Node.js provides the foundation for developing powerful, real-time, and scalable server-side applications. This guide has walked you through many ways to install and manage Node.js on Ubuntu, Alma Linux, Rocky Linux, and Fedora. Following these methods, make sure your development environment stays current, secure, and ready for any project.
Happy coding with Node.js!
About the writer
Vinayak Baranwal wrote this article. Use the provided link to connect with Vinayak on LinkedIn for more insightful content or collaboration opportunities.