Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error run .mjs file #4591

Open
YuriyTigiev opened this issue Jan 29, 2020 · 31 comments
Open

Error run .mjs file #4591

YuriyTigiev opened this issue Jan 29, 2020 · 31 comments

Comments

@YuriyTigiev
Copy link

What's going wrong?

When I run pm2 start index.mjs -e logs/err.log I get an error

PS C:\Users\yuriy\Documents\Projects\testpm2> npm -v
6.13.6
PS C:\Users\yuriy\Documents\Projects\testpm2> node -v
v13.7.0

Error [ERR_REQUIRE_ESM] [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:\Users\yuriy\Documents\Projects\testpm2\index.mjs
    at Module.load (internal/modules/cjs/loader.js:998:11)
    at Function.Module._load (internal/modules/cjs/loader.js:899:14)
    at Object.<anonymous> (C:\Users\yuriy\AppData\Roaming\npm\node_modules\pm2\lib\ProcessContainerFork.js:78:21)
    at Module._compile (internal/modules/cjs/loader.js:1151:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1171:10)
    at Module.load (internal/modules/cjs/loader.js:1000:32)
    at Function.Module._load (internal/modules/cjs/loader.js:899:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47

index.mjs

import express from 'express';
const app = express();
const port = 3000;
app.listen(port, () => console.log(`App running on port  + ${port}`));

package.json

{
  "name": "testpm2",
  "version": "1.0.0",
  "engines": {
    "node": ">=13.0.0"
  },
  "description": "",
  "main": "index.mjs",
  "type": "module",
  "scripts": {},
  "repository": {
    "type": "git",
    "url": "git+https://github.com/YuriyTigiev/testpm2.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/YuriyTigiev/testpm2/issues"
  },
  "homepage": "https://github.com/YuriyTigiev/testpm2#readme",
  "devDependencies": {
    "cross-env": "^6.0.3",
    "eslint": "^6.8.0",
    "eslint-config-standard": "^14.1.0",
    "eslint-plugin-import": "^2.20.0",
    "eslint-plugin-node": "^11.0.0",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-standard": "^4.0.1"
  },
  "dependencies": {
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "module-js": "^7.0.1"
  }
}

ecosystem.config.mjs

export const apps = [
  {
    name: 'myapp',
    script: './index.mjs',
    watch: true,
    env: {
      'PORT': 3000,
      'NODE_ENV': 'development'
    }
  }
];

How could we reproduce this issue?

$ pm2 report
pm2 report doesn't work on windows 10 

image

image

@Unitech
Copy link
Owner

Unitech commented Jan 29, 2020

Which pm2 version?

@YuriyTigiev
Copy link
Author

2.9.2-next

@Unitech
Copy link
Owner

Unitech commented Jan 30, 2020

upgrade to latest

npm install pm2@latest -g
pm2 update

it will works

@Unitech Unitech closed this as completed Jan 30, 2020
@YuriyTigiev
Copy link
Author

I did as you wrote and now I got another error

After run the script every a few seconds appears two dos screens and they hide immediately and it happens constantly until I stop the script by a command.

pm2 start index.mjs -e logs/err.log

pm2 stop 0
pm2 --version 
4.2.3
(node:8776) ExperimentalWarning: The ESM module loader is experimental.
Error [ERR_UNSUPPORTED_ESM_URL_SCHEME]: Only file and data URLs are supported by the default ESM loader
    at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:33:11)
    at Loader.resolve (internal/modules/esm/loader.js:85:40)
    at Loader.getModuleJob (internal/modules/esm/loader.js:188:40)
    at Loader.import (internal/modules/esm/loader.js:163:28)
    at importModuleDynamically (internal/modules/cjs/loader.js:1094:27)
    at exports.importModuleDynamicallyCallback (internal/process/esm_loader.js:37:14)
    at Object.<anonymous> (C:\Users\yuriy\AppData\Roaming\npm\node_modules\pm2\lib\ProcessContainerFork.js:29:24)
    at Module._compile (internal/modules/cjs/loader.js:1151:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1171:10)
    at Module.load (internal/modules/cjs/loader.js:1000:32) {
  code: 'ERR_UNSUPPORTED_ESM_URL_SCHEME'
}

@Unitech
Copy link
Owner

Unitech commented Jan 31, 2020

Could you share me a sample app so I can try this

@Unitech Unitech reopened this Jan 31, 2020
@YuriyTigiev
Copy link
Author

This is a test project for testing pm2.

testpm2.zip

@YuriyTigiev
Copy link
Author

Any updates?

@AndrewIsh
Copy link

AndrewIsh commented Mar 31, 2020

I'm also seeing this, although I'm using Node 12.16.1 (LTS) which doesn't require the .mjs extension. I have { type: "module" } in my package.json, I believe my ecosystem.config.js is correct:

export default {
    apps: [
        {
            name: 'ems-api',
            script: 'app.js',
            instances: 1,
            autorestart: true,
            watch: true,
            max_memory_restart: '1G',
            env: {
                NODE_ENV: 'development'
            },
            env_production: {
                NODE_ENV: 'production'
            }
        }
    ]
};

and the error:

[PM2][ERROR] File ecosystem.config.js malformated
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /home/ems/ems-api/ecosystem.config.js            
require() of ES modules is not supported.
require() of /home/ems/ems-api/ecosystem.config.js from /usr/lib/node_modules/pm2/lib/Common.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename ecosystem.config.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /home/ems/ems-api/package.json.
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1174:13)                                
    at Module.load (internal/modules/cjs/loader.js:1002:32)                                                  
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)     export default {
    apps: [
        {
            name: 'ems-api',
            script: 'app.js',
            instances: 1,
            autorestart: true,
            watch: true,
            max_memory_restart: '1G',
            env: {
                NODE_ENV: 'development'
            },
            env_production: {
                NODE_ENV: 'production'
            }
        }
    ]
};                                    
    at Module.require (internal/modules/cjs/loader.js:1044:19)                                               
    at require (internal/modules/cjs/helpers.js:77:18)
    at Object.Common.parseConfig (/usr/lib/node_modules/pm2/lib/Common.js:289:12)                            
    at API._startJson (/usr/lib/node_modules/pm2/lib/API.js:957:25)                                          
    at API.start (/usr/lib/node_modules/pm2/lib/API.js:333:12)                                               
    at /usr/lib/node_modules/pm2/lib/binaries/CLI.js:286:13                                                  
    at /usr/lib/node_modules/pm2/node_modules/async/internal/withoutIndex.js:8:40 {                          
  code: 'ERR_REQUIRE_ESM'
}

@tnokin
Copy link

tnokin commented May 18, 2020

I had to patch pm2 v4.4 on my PC to solve this - issue is that path.resolve() returns "c:..." on Windows, and the ESM "import" does not accepts it. I had to patch pm2\lib\ProcessContainer.js with this (discusting) code:
if (ProcessUtils.isESModule(script) === true) {
let x = process.env.pm_exec_path;
if (x.startsWith("c:")) x = x.substring(2);
x = x.replace(/\/g, "/");
import(x);
If anyone has a better solution...

@stale
Copy link

stale bot commented Jun 17, 2020

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@stale stale bot added the stale label Jun 17, 2020
@chrisstone07
Copy link

@AndrewIsh I'm facing the same issue, have you got this issue fixed?

@stale stale bot removed the stale label Jun 24, 2020
@AndrewIsh
Copy link

@AndrewIsh I'm facing the same issue, have you got this issue fixed?

I ended up side stepping the whole thing by switching from import to require

@chrisstone07
Copy link

Oh well, that's definitely not an option for me :( Hope someone can get mjs to work on node 12.18 and pm2 4.4.0.

@stale
Copy link

stale bot commented Jul 24, 2020

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@stale stale bot added the stale label Jul 24, 2020
@MastroBoy
Copy link

MastroBoy commented Aug 3, 2020

@tnokin thanks, I had to change your code a little to this in pm2\lib\ProcessContainer.js

if (ProcessUtils.isESModule(script) === true){
let x = process.env.pm_exec_path;
if (x.startsWith("C:",0)){
x = x.substring(2);
let pathSep = '\'; <- double slash not one
x = x.replace(new RegExp('\' + pathSep, 'g'), '/'); <- double slash not one
}
import(x);
//import(process.env.pm_exec_path); <-- commented out
}else{
require('module')._load(script, null, true);
}

@stale stale bot removed the stale label Aug 3, 2020
@clshortfuse
Copy link

I'm guessing PM2 doesn't support ESM on Windows. For those in a pinch, https://github.com/coreybutler/node-windows after you install it as a service.

@kostadinSpiridonov
Copy link

kostadinSpiridonov commented Aug 7, 2020

Is there a plan for fixing this issue at all since we are experiencing the same behavior?

@Smilebags
Copy link

Sad this isn't supported. It'd be really nice to be able to use standard Node features in apps even when running through pm2.

@SammyWhamy
Copy link

I also had the same issue, the workaround I found is to use
pm2 start node -- .
This way pm2 starts up node which starts your app. In my case I use . (Starts the main: entry in package.json), but I'm sure you can also use pm2 start node -- server.js or pm2 start npm -- start (I haven't tried these, but I don't see why they wouldn't work).

I run a discord bot and for some reason if I add --watch it restarts my bot every time I do a command, this might be a side effect from using this work around. Although I can't be sure since I can't get my bot to run with pm2 start server.js.

I've also tried to run pm2 start nodemon -- server.js as a workaround to the --watch issue but that throws a syntax error for:
@ECHO off in the nodemon package

@ghost
Copy link

ghost commented Aug 23, 2020

Thanks @SammyWhamy, that worked for me on Windows 10, node v14.8.0, pm2 v4.4.1

@microJ
Copy link

microJ commented Sep 13, 2020

thanks @SammyWhamy , use pm2 start node -- app.js is worked。
but use node ./job/checkMongoDB.js && pm2 start node -- app.js doesn't work,it's confused 🤣

@andbridge
Copy link

oh ,on,how can we used pm2 start a project with the ecosystem.config.js.

@andbridge
Copy link

我也遇到了同样的问题,我看了上面的解决方式,发现运行的模式是fork,并且我想知道如何通过ecosystem.config.js进行运行一个项目,我已经更新到pm2最新版本,并且尝试着去运行这样一行命令,pm2 start ecosystem.config.js,我的cmd窗口出现了正常的运行界面如下图:
1616987313(1)
但是我的错误日志里却有着这样的报错:
You have triggered an unhandledRejection, you may have forgotten to catch a Promise rejection: Error [ERR_UNSUPPORTED_ESM_URL_SCHEME]: Only file and data URLs are supported by the default ESM loader. On Windows, absolute paths must be valid file:// URLs. Received protocol 'e:' at new NodeError (node:internal/errors:329:5) at Loader.defaultResolve [as _resolve] (node:internal/modules/esm/resolve:841:11) at Loader.resolve (node:internal/modules/esm/loader:86:40) at Loader.getModuleJob (node:internal/modules/esm/loader:230:28) at Loader.import (node:internal/modules/esm/loader:165:28) at importModuleDynamically (node:internal/modules/cjs/loader:1032:29) at importModuleDynamicallyWrapper (node:internal/vm/module:437:21) at importModuleDynamically (node:vm:387:43) at exports.importModuleDynamicallyCallback (node:internal/process/esm_loader:30:14) at E:\code\ncpnode\node_modules\pm2\lib\ProcessContainer.js:301:26

@HishamMubarak
Copy link

HishamMubarak commented Apr 24, 2021

Added "type": "module" in package.json of my node and that caused this error.

Was able to get it fixed by renaming ecosystem.config.js to ecosystem.config.cjs, cjs file extension

@andbridge
Copy link

Added "type": "module" in package.json of my node and that caused this error.

Was able to get it fixed by renaming ecosystem.config.js to ecosystem.config.cjs, cjs file extension

谢谢,在liunx上没有问题

@ejames17
Copy link

thanks @SammyWhamy , use pm2 start node -- app.js is worked。 but use node ./job/checkMongoDB.js && pm2 start node -- app.js doesn't work,it's confused 🤣

Not sure why it doesn't work even with the latest pm2

@arikon
Copy link

arikon commented Mar 17, 2023

This chunk of code should be fixed. In case of .mjs extension import() should be used to load config, not require().

https://github.com/Unitech/pm2/blob/master/lib/Common.js#L314-L318

  else if (filename.indexOf('.config.js') > -1 || filename.indexOf('.config.cjs') > -1 || filename.indexOf('.config.mjs') > -1) {
    var confPath = require.resolve(path.resolve(filename));
    delete require.cache[confPath];
    return require(confPath);
  }

@orgads
Copy link

orgads commented Apr 3, 2023

Fixed in #5524. Please close.

@arikon
Copy link

arikon commented Apr 4, 2023

@orgads Which version contains the fix?

@orgads
Copy link

orgads commented Apr 4, 2023

5.3.0.

@rambo-panda
Copy link

rambo-panda commented Apr 27, 2024

pm2: v5.3.1

It seems to be unsolvable

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests