Node.js is an open-source, cross-platform JavaScript runtime environment that executes JavaScript code server-side. It’s incredibly popular for building scalable and high-performance network applications. Node.js applications are written in JavaScript and can be run on various operating systems, including OS X, Microsoft Windows, Linux, FreeBSD, IBM AIX, IBM System z, and IBM i.

This guide will walk you through the process of installing Node.js and npm (Node Package Manager) on CentOS 6.6, along with essential tools and a basic example to ensure everything is working correctly.

Installing nodejs and npm on CentOS 6.6

These steps outline the process of adding the NodeSource repository and installing Node.js and npm using yum. NodeSource provides updated and supported versions of Node.js.

  1. Gain Root Privileges: Start by switching to the root user. This is necessary to install software packages.

    [nodejs-admin@nodejs ~]$ sudo su
    
  2. Add the NodeSource Repository: This command downloads and executes a script from NodeSource that configures your system to use their repository for Node.js packages.

    [nodejs-admin@nodejs ~]# curl -sL https://rpm.nodesource.com/setup | bash -
    

    Explanation:

    • curl: A command-line tool for transferring data with URLs.
    • -sL: -s (silent mode) suppresses progress and error messages. -L (follow redirects) ensures the script is downloaded even if the URL redirects.
    • | bash -: Pipes the downloaded script directly to the bash interpreter for execution. Important: Always inspect scripts from the internet before executing them.
  3. Install Node.js: This command uses the yum package manager to install Node.js and its dependencies from the NodeSource repository. This will also install npm which comes bundled with nodejs.

    [nodejs-admin@nodejs ~]# yum install -y nodejs
    

    Explanation:

    • yum: The Yellowdog Updater, Modified, is a package manager for RPM-based Linux distributions like CentOS.
    • install: Tells yum to install a package.
    • -y: Automatically answers “yes” to any prompts during the installation process.

Installing gcc-c++ and make

These tools are often required for building native Node.js modules (add-ons). gcc-c++ is the C++ compiler and make is a build automation tool.

[nodejs-admin@nodejs ~]$ sudo yum install gcc-c++ make

Explanation:

  • gcc-c++: The GNU C++ compiler, necessary for compiling C++ code. Many Node.js modules rely on native C++ components for performance or access to system-level APIs.
  • make: A build automation tool that reads a Makefile to determine how to compile and link software.

The output you provided indicates that make is already installed. yum will install gcc-c++ and any other missing dependencies.

Installing kafka-node

This step installs the kafka-node npm package, which is a Node.js client for Apache Kafka. Kafka is a distributed streaming platform often used for building real-time data pipelines and streaming applications.

[nodejs-admin@nodejs ~]$ sudo npm install kafka-node

Explanation:

  • npm: The Node Package Manager, used to install and manage Node.js packages.
  • install: Tells npm to install a package.
  • kafka-node: The name of the package to install.

The output shows that npm is installing kafka-node and its dependencies, including snappy. The gyp WARN EACCES messages indicate permission issues during the installation of snappy. This might not be a problem, but to avoid potential issues, consider the following:

  • Avoid sudo with npm: It’s generally recommended not to use sudo with npm unless absolutely necessary. Instead, configure npm to use a directory that your user account owns.
  • Fix Permissions (if necessary): If you encounter errors later due to these permission issues, you can change the ownership of the .node-gyp directory: sudo chown -R $USER:$GROUP ~/.node-gyp

After the installation completes, npm lists the installed packages and their dependencies.

Testing Your Installation

Let’s create a simple “Hello World” Node.js server to verify that Node.js is installed correctly.

  1. Create example.js: Create a new file named example.js and paste the following code into it:

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

    Explanation:

    • require('http'): Imports the built-in http module.
    • http.createServer(...): Creates an HTTP server.
    • function (req, res) { ... }: A callback function that handles incoming requests. req is the request object, and res is the response object.
    • res.writeHead(200, {'Content-Type': 'text/plain'}): Sets the HTTP response status code to 200 (OK) and the Content-Type header to text/plain.
    • res.end('Hello World\n'): Sends the “Hello World” message as the response body and ends the response.
    • .listen(1337, '127.0.0.1'): Starts the server and listens for incoming connections on port 1337 on the loopback address (127.0.0.1).
    • console.log(...): Prints a message to the console.
  2. Start the Server: Run the script using the node command:

    [nodejs-admin@nodejs nodejs]$ node example.js
    

    You should see the message “Server running at http://127.0.0.1:1337/” in the terminal.

  3. Access the Server in a Browser: Open a web browser and navigate to http://127.0.0.1:1337/. You should see the “Hello World” message displayed in your browser.

If you see “Hello World,” your Node.js installation is working correctly!

Handling JSON Data

This example demonstrates how to create a simple Node.js server that receives and logs JSON data.

//  Getting some 'http' power
var http=require('http');

//  Setting where we are expecting the request to arrive.
//  http://localhost:8125/upload
var request = {
                hostname: 'localhost',
                port: 8125,
                path: '/upload',
                method: 'GET'
            };

//  Lets create a server to wait for request.
http.createServer(function(request, response)
{
    //  Making sure we are waiting for a JSON.
    response.writeHeader(200, {"Content-Type": "application/json"});

    //  request.on waiting for data to arrive.
    request.on('data', function (chunk)
    {
        //  CHUNK which we recive from the clients
        //  For out request we are assuming its going to be a JSON data.
        //  We print it here on the console.
        console.log(chunk.toString('utf8'))
    });
    //end of request
    response.end();
//  Listen on port 8125
}).listen(8125);

Explanation:

  • The script sets up an HTTP server listening on port 8125.
  • It sets the Content-Type header to application/json to indicate that it expects to receive JSON data.
  • The request.on('data', ...) event listener captures incoming data chunks from the client.
  • chunk.toString('utf8') converts the data chunk (which is a buffer) to a UTF-8 string.
  • console.log(...) prints the received JSON data to the console.
  1. Save the Script: Save the above code as node_recv_json.js.

  2. Start the Server: Run the script:

    [nodejs-admin@nodejs nodejs]$ node node_recv_json.js
    
  3. Send a JSON Request: Use curl to send a JSON payload to the server:

    [nodejs-admin@nodejs nodejs]$ curl -H "Content-Type: application/json" \
                                -d '{"username":"xyz","password":"xyz"}' http://localhost:8125/upload
    

    Explanation:

    • curl -H "Content-Type: application/json": Sends an HTTP request with the Content-Type header set to application/json.
    • -d '{"username":"xyz","password":"xyz"}': Sends the JSON data {"username":"xyz","password":"xyz"} as the request body.
    • http://localhost:8125/upload: The URL of the server endpoint.
  4. Verify the Output: In the terminal where the Node.js script is running, you should see the received JSON data:

    {"username":"xyz","password":"xyz"}
    

You are now ready to experiment and build more complex Node.js applications! This guide provides a solid foundation for developing server-side applications with Node.js on CentOS 6.6. Remember to keep your system updated and consult the official Node.js documentation for more in-depth information.