Migrating an existing Node.js application to Node.js Selector

Learn how to migrate your Node.js application to cPanel's Node.js Selector. Just follow our easy step-by-step instructions!

This article describes how to migrate an existing Node.js application to the Node.js Selector in cPanel.

Migrating an application

In most cases, Node.js applications can be migrated to Node.js Selector with only minor modifications. To do this, follow these steps:

  1. Log in to cPanel.

    📘

    Note

    If you do not know how to log in to your cPanel account, please see this article.

  2. Create a new application using Node.js Selector.

    📘

    Note

    For information about how to create a new Node.js application using the Node.js Selector in cPanel, please see this article.

  3. Copy the existing Node.js application files to the application root directory.

  4. Modify the script files for the Node.js Selector environment as follows:

  • Port number: If your existing application uses a hard-coded port number, you should change it to obtain a port number dynamically. The exact method to do this varies based on the application. For example, consider the following Express Node.js application code, which uses port 3000:
const express = require('express')
const app = express()
const port = 3000

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

app.listen(port, () => console.log('Example app listening at http://localhost:${port}'))

This code can be modified to obtain a port number dynamically as follows:

const express = require('express')
const app = express()

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

const server = app.listen(0, () => {
    console.log('Example app listening at http://localhost:', server.address().port);
});

The parameter 0 in the app.listen() statement instructs Node.js to obtain a port number dynamically.

  • Import directives: Some Node.js versions do not support import directives. Therefore, you should modify any import statements to use require instead. For example, consider the following statements:
import express from "express";
import path from "path";
import dotenv from "dotenv";

These statements can be modified to work correctly as follows:

const express = require('express');
const path = require('path');
const dotenv = require('dotenv');
  • Routes: You may have to modify the routes in your code to include the application URL. For more information, please see this article.

Related Articles