skip to Main Content

I am trying to run my Node.js application on a Namecheap server using the Node.js Selector, but it’s unable to start up because it’s requireing the startup file

Startup file (I don’t think I can just change to cjs, as my actual app is Nuxt 3. This is just an example):

import http from 'http';
var server = http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    var message = 'It works!n',
        version = 'NodeJS ' + process.versions.node + 'n',
        response = [message, version].join('n');
    res.end(response);
});
server.listen();

Error:

internal/modules/cjs/loader.js:948
    throw new ERR_REQUIRE_ESM(filename);
    ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /home/wiebdmbt/jawedding/app.mjs
    at new NodeError (internal/errors.js:322:7)
    at Module.load (internal/modules/cjs/loader.js:948:11)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:93:18)
    at startApplication (/usr/local/lsws/fcgi-bin/lsnode.js:48:15)
    at Object.<anonymous> (/usr/local/lsws/fcgi-bin/lsnode.js:16:1)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32) {
  code: 'ERR_REQUIRE_ESM'
}

2

Answers


  1. In my case, the version of Node Selector installed in my "Namecheap server" didn’t support ES modules. Since it was a small application (which is the only kind of application you should be running on a cheap hosting service), I was able to edit the whole app to use CommonJS modules. It was a huge waste of time though. I migrated to ES modules in the first place because I wanted to use the newest version of node-fetch only to discover that Node Selector was not compatible with the new changes. I hope you had better luck!

    Login or Signup to reply.
  2. The problem is that common js can not require ES modules.

    To work around this, create a cjs wrapper around your code by doing this:

    1. Create a common js (cjs) file, say myloader.cjs.
    2. Rename your ‘entry file’ to .mjs. In your case, app.mjs
    3. Add the following piece of code to the myloader.cjs
    async function loadApp() {
        await import("/path/to/app.mjs");
    }
    
    loadApp();
    
    1. Change the application startup file in the node js setup to myloader.cjs.
    2. Also change the main entry in package.json to myloader.cjs
    "main": "myloader.cjs",
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search