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 require
ing 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
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!
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:cjs
) file, saymyloader.cjs
..mjs
. In your case,app.mjs
myloader.cjs
myloader.cjs
.main
entry in package.json tomyloader.cjs