How to migrate an existing Node.js application to Node.js Selector

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

Table of Contents

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.
    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.
    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.

Did you find this article helpful? Then you'll love our support. Experience the A2 Hosting difference today and get a pre-secured, pre-optimized website. Check out our web hosting plans today.

We use cookies to personalize the website for you and to analyze the use of our website. You consent to this by clicking on "I consent" or by continuing your use of this website. Further information about cookies can be found in our Privacy Policy.