Skip to main content

Install Node.js on CentOS

This is our guide on installing Node.js on CentOS, a robust and stable Linux distribution favored by many system administrators and developers. Node.js is a JavaScript runtime environment that allows you to run JavaScript on the server side, enabling the development of scalable network applications. Before we dive into the installation process, let's understand what Node.js is and why you might want to install it on CentOS.

What is Node.js?

Node.js is an open-source, cross-platform JavaScript runtime environment that executes JavaScript code outside of a browser. It's built on Chrome's V8 JavaScript engine, which is known for its high performance and speed. Node.js uses an event-driven, non-blocking I/O model, making it lightweight and efficient, especially for data-intensive real-time applications that run across distributed devices.

Developers love Node.js for its ability to use JavaScript for both client-side and server-side development, which can streamline the development process and improve performance. It's also supported by a vast ecosystem of packages through the Node Package Manager (npm), which simplifies the inclusion of additional functionalities in your applications.

What is CentOS?

CentOS (Community Enterprise Operating System) is a Linux distribution derived from the sources of Red Hat Enterprise Linux (RHEL). It's known for its stability, predictability, and long-term support, making it an excellent choice for servers and production environments.

By installing Node.js on CentOS, you're setting up a reliable and powerful platform for developing and deploying your Node.js applications. Whether you're building a RESTful API, a real-time chat application, or a single-page application (SPA), Node.js on CentOS can be a solid foundation.

Prerequisites

  • A CentOS-based system (CentOS 7 or 8).
  • Access to a user with sudo privileges.
  • Basic knowledge of using the command line.

Step 1: Updating the System

Before we begin the installation, it's a good practice to update your system to the latest packages. This ensures that you have the latest security patches and software updates.

sudo yum update -y

Our output:.

CentOS-7 - Updates                                                                                                                                                    3.7 MB/s | 13 MB     00:03
...
Complete!

Step 2: Installing Node.js

There are several methods to install Node.js on CentOS. We'll cover the two most common approaches: using Node Version Manager (nvm) and using the NodeSource repository.

Method 1: Using Node Version Manager (nvm)

nvm is a tool that allows you to install and manage multiple versions of Node.js. It's particularly useful if you need to switch between different Node.js versions for various projects.

Installing nvm

  1. First, you need to install some prerequisites:.
sudo yum install -y git gcc-c++ make
  1. Next, install nvm using the install script from the nvm GitHub repository:.
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
  1. To start using nvm, you'll need to log out and log back in, or you can source the nvm profile file:.
source ~/.bash_profile
  1. Verify that nvm was installed correctly:.
nvm --version

Expected output:.

0.39.1

Installing Node.js via nvm

  1. Install the latest version of Node.js:.
nvm install node
  1. Set the latest version as the default Node.js version:.
nvm alias default node
  1. Verify the installation:.
node -v
npm -v

Our output:.

v16.13.0
6.14.8

Method 2: Using the NodeSource Repository

NodeSource provides a repository containing Node.js packages for CentOS, which makes it easy to install and keep Node.js up to date.

  1. Choose the version of Node.js you want to install. You can find the latest versions and their corresponding commands on the NodeSource GitHub page. For example, to install Node.js 16.x, you would use:.
curl -sL https://rpm.nodesource.com/setup_16.x | sudo bash -
  1. Install Node.js:.
sudo yum install -y nodejs
  1. Verify the installation:.
node -v
npm -v

Expected output:.

v16.13.0
6.14.8

Step 3: Managing Node.js Versions (nvm only)

If you installed Node.js using nvm, you could easily switch between different versions of Node.js. Here's how:.

  1. To list the Node.js versions available for installation:.
nvm ls-remote
  1. To install a specific version of Node.js:.
nvm install 14.17.0
  1. To switch to a different version of Node.js:.
nvm use 14.17.0
  1. To set a default Node.js version:.
nvm alias default 14.17.0

Step 4: Configuring npm

npm, the Node.js package manager, can be configured to suit your needs. Here are a few common configuration steps:.

  1. Set the default registry (if you want to use a different one):.
npm config set registry https://registry.npmjs.org/
  1. Configure npm to not require sudo for installing packages globally:.
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'

Add the following line to your ~/.bash_profile or ~/.bashrc:.

export PATH=~/.npm-global/bin:$PATH

Then, source your profile file:.

source ~/.bash_profile
  1. Install a global package without sudo:.
npm install -g <package-name>

Step 5: Setting Up a Node.js Project

Now that you have Node.js installed, let's set up a simple project:.

  1. Create a new directory for your project and navigate into it:.
mkdir my-node-project && cd my-node-project
  1. Initialize a new Node.js project:.
npm init -y

This will create a package.json file with default values.

  1. Add a dependency to your project, for example, express:.
npm install express
  1. Create a simple index.js file:.
const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
res.send('Hello World!');
});

app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
  1. Run your application:.
node index.js

Expected output:.

Example app listening at http://localhost:3000

Example 2 - Create a Node.js HTTP Server

The previous example was an Express Server. However we can also create an example using Node.js itself without any third party installations.

Create a new file named server.js with the following code:

const http = require('http');

const hostname = 'localhost';
const port = 3000;

const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World!');
});

server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});

Save the file and run the following command to start the server:

node server.js

You should see the following output:

Server running at http://localhost:3000/

Open a web browser and go to http://localhost:3000/. You should see the message "Hello World!".

Security Considerations

  • Always keep Node.js and your npm packages up to date to ensure you have the latest security patches.
  • Use npm audit regularly to identify and fix security vulnerabilities in your project dependencies.

Troubleshooting Common Issues

  • If you encounter permission issues with global npm packages, ensure you've configured npm to use a directory you have write access to, as described in the npm configuration section.
  • If Node.js doesn't work after installation, make sure the correct version is being used with node -v and npm -v. If you're using nvm, you may need to switch to the correct version with nvm use <version>.

Summary

You've successfully installed Node.js on your CentOS system and set up a basic Node.js project. Whether you chose to use nvm for version management or installed directly from the NodeSource repository, you're now ready to develop and deploy Node.js applications on CentOS.

Further Reading

Appendix: Uninstalling Node.js

If you need to uninstall Node.js from your CentOS system, the process will depend on how you installed it.

  • If you used nvm:.
nvm uninstall <version>
  • If you used the NodeSource repository:.
sudo yum remove -y nodejs

Remember to remove any global npm packages you installed if you're completely removing Node.js from your system.

By following this guide, you should have a solid understanding of how to install, configure, and manage Node.js on CentOS. Enjoy building your Node.js applications!