How to install Node.js and NPM on CentOS

Introduction

Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js’ package ecosystem, npm, is the largest ecosystem of open source libraries in the world. In this article we will explain the steps of installing node.js and npm in CentOS.

Step 1: Add node.js yum repository

First we need to add yum repository of node.js to our system which is sourced from nodejs’ official website. Run the following commands in succession to add the yum repository.

yum install -y gcc-c++ make
curl -sL https://rpm.nodesource.com/setup_6.x | sudo -E bash -

Step 2: Install node.js and NPM

Now it’s time to install the node.js package and NPM package. Run the following command to do so. This single command will install node.js, npm and also other dependent packages.

yum install nodejs

Step 3: Verify versions

Having installed the packages, you need to check their versions.

For checking node.js version:

node -v

#output
v6.9.4

For checking npm version:

npm -v

#output
3.10.10

Step 4: Testing the installation

You can test your installation by creating a test file, say test_server.js

vim test_server.js

Then add the following content in the file.

var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Welcome');
}).listen(3001, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3001/');

Now start the web server using the below command

node --debug test_server.js

debugger listening on port 5858
Server running at http://127.0.0.1:3001/

Web server has started which can be accessed using URL http://127.0.0.1:3001/ in your browser.