CommonJS and ES6 with NodeJS

Hello I made an Express JS app with Node Js 16

The index file is

const express = require('express');

const app = express();
const port = 3000;

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

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

This app work but if I convert it to ES6 app and the file will look like this then

import express from 'express';

const app = express();
const port = 3000;

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

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

So we change the import to import express from 'express';

Also we need to add "type": "module", to our package.json file so the file will look like this:

{
  "name": "index",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "start": "node index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
  "dependencies": {
    "express": "~4.16.1",
  }
}

The problem is that when I convert the app to ES6 and then go to the app from domain.com, the app dose not work and the page still loading then nothing come up like below.

The command line tells me that both apps are listen to


> node index.js

Example app listening on port 3000!

But the ES6 dose not work.

I made the same steps with my PC in localhost and everthing worked well but in the Cypber Panel this is dose not work.

Hello @maher.aldous Happy you are here

You need to server common js.

In your application you have to convert your emascript to common js format.If this is just an express app you can setup transpiler like babel (plugin-transform-modules-commonjs is a perfect example and easy to use) and rollup to bundle your code or use frameworks such as adonisjs that support es6 scripting

I tried to "transpile": "babel index.js --out-dir dist" then "startnd": "node dist/index.js",

Like in package.json

{
  "name": "public_html",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "nodemon --exec babel-node index.js",
    "start": "babel-node index.js",
    "startn": "node index.js",
    "startd": "babel-node dist/index.js",
    "startnd": "node dist/index.js",
    "transpile": "babel index.js --out-dir dist"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@babel/preset-env": "^7.20.2",
    "body-parser": "^1.20.1",
    "cors": "^2.8.5",
    "express": "^4.18.2",
    "nodemon": "^2.0.20"
  },
  "devDependencies": {
   "@babel/cli": "^7.8.4",
    "@babel/core": "^7.20.5",
    "@babel/node": "^7.20.5",
    "@babel/plugin-transform-modules-commonjs": "^7.19.6",
     "babel-cli": "^6.26.0"
  }
}

In .babelrc file

{
  "presets": [
    "@babel/preset-env"
  ],
  "plugins": ["@babel/plugin-transform-modules-commonjs"]
}

But nothing happen also when I go back Common JS to test without ES6 now like here

const express = require('express'); // Add this line that worked before but not now
// import express from 'express'; // Delete this line that not work

const app = express();
const port = 3000;

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

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

Nothing work. Before I could at least use Common JS and I made a fresh app again but only with Common JS but seems even with the fresh app the Common JS won’t work.

Sorry for bothering you but do you want to get access to the server to see everthing. It’s ok because it just a test server.

Hello @maher.aldous Hope you are well

This is uneccessary. Why dont you do something simpler like GitHub - hiteshsahu/Node-JS-ES6: Simple setup for using ES6 in Node JS server

You should not be using babel-node in production. It is unnecessarily heavy, with high memory usage due to the cache being stored in memory. Also due to technical limitations ES6-style module-loading is not fully supported.

Hello

Sorry for late replay.

I tried your way on my local computer which is running Windows 11 and it worked

I tried on the server and it worked but the app keep crashing when I start it even in my local computer so I found another code.

This one is the code

On my local computer this code work and I can see the home page

When I run this code on the server with Cyberpanel I see in the terminal that it is working but when I go to test.graphqltest.ml:3000 I don’t get anything
image

Best Regards
Maher Aldous

Happy New Year @maher.aldous

OLS/LiteSpeed Web Server acts as a frontend proxy to the Node.js backend via a unix domain socket without the need for separate web application server like Phusion.

Now with that said the key here is to proxy all our nodejs traffic using lsws

This is a good start however to deploy our “api” project I recommend a process manager like PM2.

$ npm install pm2 -g
# add app to pm2
$ pm2 start dist/app.js --name "es6-setup-node" --watch
# daemonize your app
$ pm2 startup && pm2 save
# to see all your node apps
$ pm2 list
# Display all apps logs in realtime
$ pm2 monit

Then proxy your app traffic by setting up an appserver context Setup Express.js Application on CyberPanel/OpenLiteSpeed

This assumes you have a domain so visit you app api.mydomain.com

Hello

Thank you and Happy New Year for you too

I know about the link you shared with me and I have this setup before and I checked it and it still the same.

I also used your commands and installed pm2.

I don’t know how to mange proxy in this situation and I did some search before I replay to you but still there is no answer.

I have also activated access to the OpenLiteSpeed itself but I don’t know what to do.

This is my vHost Conf

docRoot                   $VH_ROOT/public_html
vhDomain                  $VH_NAME
vhAliases                 www.$VH_NAME
adminEmails             [email protected]
enableGzip                1
enableIpGeo               1

errorlog $VH_ROOT/logs/$VH_NAME.error_log {
  useServer               0
  logLevel                WARN
  rollingSize             10M
}

accesslog $VH_ROOT/logs/$VH_NAME.access_log {
  useServer               0
  logFormat               "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i""
  logHeaders              5
  rollingSize             10M
  keepDays                10
  compressArchive         1
}

index  {
  useServer               0
  indexFiles              index.php, index.html
}

scripthandler  {
  add                     lsapi:testg2419 php
}

extprocessor testg2419 {
  type                    lsapi
  address                 UDS://tmp/lshttpd/testg2419.sock
  maxConns                10
  env                     LSAPI_CHILDREN=10
  initTimeout             600
  retryTimeout            0
  persistConn             1
  pcKeepAliveTimeout      1
  respBuffer              0
  autoStart               1
  path                    /usr/local/lsws/lsphp74/bin/lsphp
  extUser                 testg2419
  extGroup                testg2419
  memSoftLimit            2047M
  memHardLimit            2047M
  procSoftLimit           400
  procHardLimit           500
}

context /.well-known/acme-challenge {
  location                /usr/local/lsws/Example/html/.well-known/acme-challenge
  allowBrowse             1
  addDefaultCharset       off
}

context / {
  type                    appserver
  location                /home/test.graphqltest.ml/public_html
  binPath                 /usr/bin/node
  appType                 node
  maxConns                100
  addDefaultCharset       off
}

rewrite  {
  enable                  1
  autoLoadHtaccess        1
}

vhssl  {
  keyFile                 /etc/letsencrypt/live/test.graphqltest.ml/privkey.pem
  certFile                /etc/letsencrypt/live/test.graphqltest.ml/fullchain.pem
  certChain               1
  enableECDHE             1
  renegProtection         1
  sslSessionCache         1
  enableSpdy              15
  enableStapling          1
  ocspRespMaxAge          86400
}

module cache {
storagePath /usr/local/lsws/cachedata/$VH_NAME
}


The Node JS server is working with both syntax the Common JS and the ES6 but the home page only visible on Common JS.

Would you like to give you all the access via email.

I don’t have anything important there. You can do what you want even deleting everything.

What I want is that I have the Cyber Panel on this domain https://serv.example.com/ and I want the Node JS app with the ES6 syntax to be at https://test.example.com/

In the https://example.com/ I will have my website page. That’s all. The only thing I can’t get it done is the Node JS app with the ES6 syntax not the Node JS with the Common JS.

I have only one IP address and it connected to https://example.com/. So the other domains are only subdomains.

Best Regards
Maher Aldous