Node.js on Apache server (Shared Hosting)

apachehostingnode.js

I would like to run Node.js/Express as a backend server mainly for handling WebRTC features in my app.
I was just discussing this with my hosting provider and they rejected this request saying that Node.js is heavy and requires Java thus making it impossible to run on Apache so I need to upgrade my account to VPS.

Google tells me the opposite and many people are running Node.js on Apache.

Is the above true or are they trying to take advantage of me?

Best Answer

Actually you can run node.js on a typical shared hosting with Linux, Apache and PHP. Even NPM, Express and Grunt work fine. Here are the necessary steps:

1) Create a new PHP file on the server with the following contents and run it:

<?php
//Download and extract the latest node
exec('curl http://nodejs.org/dist/latest/node-v0.10.33-linux-x86.tar.gz | tar xz');
//Rename the folder for simplicity
exec('mv node-v0.10.33-linux-x86 node');

2) Install your node app, e.g. jt-js-sample, using npm:

<?php
exec('node/bin/npm install jt-js-sample');

3) Run the node app from PHP:

<?php
//Choose JS file to run
$file = 'node_modules/jt-js-sample/index.js';
//Spawn node server in the background and return its pid
$pid = exec('PORT=81 node/bin/node ' . $file . ' >/dev/null 2>&1 & echo $!');
//Wait for node to start up
usleep(500000);
//Connect to node server using cURL
$curl = curl_init('http://127.0.0.1:81/');
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//Get the full response
$resp = curl_exec($curl);
if($resp === false) {
    //If couldn't connect, try increasing usleep
    echo 'Error: ' . curl_error($curl);
} else {
    //Split response headers and body
    list($head, $body) = explode("\r\n\r\n", $resp, 2);
    $headarr = explode("\n", $head);
    //Print headers
    foreach($headarr as $headval) {
        header($headval);
    }
    //Print body
    echo $body;
}
//Close connection
curl_close($curl);
//Close node server
exec('kill ' . $pid);

Voila! Have a look at the working demo of a node app on PHP shared hosting.

EDIT: Here is my new project Node.php on GitHub.