Unitech / pm2

Node.js Production Process Manager with a built-in Load Balancer.
https://pm2.keymetrics.io/docs/usage/quick-start/
Other
41.52k stars 2.63k forks source link

Error run .mjs file #4591

Open YuriyTigiev opened 4 years ago

YuriyTigiev commented 4 years ago

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 commented 4 years ago

Which pm2 version?

YuriyTigiev commented 4 years ago

2.9.2-next

Unitech commented 4 years ago

upgrade to latest

npm install pm2@latest -g
pm2 update

it will works

YuriyTigiev commented 4 years ago

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 commented 4 years ago

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

YuriyTigiev commented 4 years ago

This is a test project for testing pm2.

testpm2.zip

YuriyTigiev commented 4 years ago

Any updates?

AndrewIsh commented 4 years ago

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 commented 4 years ago

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[bot] commented 4 years ago

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.

chrisstone07 commented 4 years ago

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

AndrewIsh commented 4 years ago

@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 commented 4 years ago

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[bot] commented 4 years ago

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.

MastroBoy commented 4 years ago

@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); }

clshortfuse commented 4 years ago

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 commented 4 years ago

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

Smilebags commented 4 years ago

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 commented 4 years ago

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 commented 4 years ago

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

microJ commented 4 years ago

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 commented 3 years ago

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

andbridge commented 3 years ago

我也遇到了同样的问题,我看了上面的解决方式,发现运行的模式是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 commented 3 years ago

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 commented 3 years ago

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 commented 2 years ago

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 commented 1 year ago

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 commented 1 year ago

Fixed in #5524. Please close.

arikon commented 1 year ago

@orgads Which version contains the fix?

orgads commented 1 year ago

5.3.0.

rambo-panda commented 6 months ago

pm2: v5.3.1

It seems to be unsolvable

image