pm2 icon indicating copy to clipboard operation
pm2 copied to clipboard

Error run .mjs file

Open YuriyTigiev opened this issue 5 years ago • 31 comments
trafficstars

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

YuriyTigiev avatar Jan 29 '20 18:01 YuriyTigiev

Which pm2 version?

Unitech avatar Jan 29 '20 19:01 Unitech

2.9.2-next

YuriyTigiev avatar Jan 29 '20 19:01 YuriyTigiev

upgrade to latest

npm install pm2@latest -g
pm2 update

it will works

Unitech avatar Jan 30 '20 11:01 Unitech

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'
}

YuriyTigiev avatar Jan 30 '20 16:01 YuriyTigiev

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

Unitech avatar Jan 31 '20 15:01 Unitech

This is a test project for testing pm2.

testpm2.zip

YuriyTigiev avatar Jan 31 '20 15:01 YuriyTigiev

Any updates?

YuriyTigiev avatar Feb 03 '20 18:02 YuriyTigiev

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'
}

AndrewIsh avatar Mar 31 '20 13:03 AndrewIsh

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...

tnokin avatar May 18 '20 17:05 tnokin

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[bot] avatar Jun 17 '20 17:06 stale[bot]

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

chrisstone07 avatar Jun 24 '20 20:06 chrisstone07

@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

AndrewIsh avatar Jun 24 '20 20:06 AndrewIsh

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.

chrisstone07 avatar Jun 24 '20 21:06 chrisstone07

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[bot] avatar Jul 24 '20 21:07 stale[bot]

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

MastroBoy avatar Aug 03 '20 16:08 MastroBoy

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.

clshortfuse avatar Aug 06 '20 17:08 clshortfuse

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

kostadinSpiridonov avatar Aug 07 '20 07:08 kostadinSpiridonov

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.

Smilebags avatar Aug 10 '20 12:08 Smilebags

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

SammyWhamy avatar Aug 20 '20 23:08 SammyWhamy

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

ghost avatar Aug 23 '20 07:08 ghost

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 🤣

microJ avatar Sep 13 '20 18:09 microJ

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

andbridge avatar Mar 29 '21 02:03 andbridge

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

andbridge avatar Mar 29 '21 03:03 andbridge

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

HishamMubarak avatar Apr 24 '21 20:04 HishamMubarak

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上没有问题

andbridge avatar Apr 25 '21 02:04 andbridge

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

ejames17 avatar May 30 '22 17:05 ejames17

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

arikon avatar Mar 17 '23 12:03 arikon

Fixed in #5524. Please close.

orgads avatar Apr 03 '23 05:04 orgads

@orgads Which version contains the fix?

arikon avatar Apr 04 '23 19:04 arikon

5.3.0.

orgads avatar Apr 04 '23 19:04 orgads