Skip to content

How to create a Node.js application (legacy method)

This legacy guide uses cron jobs and PHP to create a persistent Node.js application. It remains available for reference.

Create a nodejs folder in your home directory (via FTP/SFTP or the cPanel File Manager), then create an app.js file inside it:

var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen('12345');
console.log('Server started');

Replace 12345 with a randomly generated 5-digit port number and note it for later steps.

Create a cron.php file in the nodejs folder:

<?php
$host = '127.0.0.1';
$port = '12345';
$checkconn = @fsockopen($host, $port, $errno, $errstr, 5);
if (empty($checkconn)) {
exec('/usr/bin/node /home/' . get_current_user() . '/nodejs/app.js > /dev/null 2>&1 &');
}

Replace 12345 with your chosen port number.

In cPanel, open Cron Jobs and create a new cron job with the command:

/usr/local/bin/php /home/username/nodejs/cron.php > /dev/null 2>&1

Replace username with your cPanel username.

Create a .htaccess file in the directory where you want the application to load (e.g., public_html):

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ http://127.0.0.1:12345/$1 [P,L]

Replace 12345 with your port number. Your Node.js application should now be accessible at that URL.