Pm2: Error run .mjs file

Created on 29 Jan 2020  Â·  21Comments  Â·  Source: Unitech/pm2

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

Most helpful comment

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

All 21 comments

Which pm2 version?

2.9.2-next

upgrade to latest

npm install pm2@latest -g
pm2 update

it will works

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

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

This is a test project for testing pm2.

testpm2.zip

Any updates?

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

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

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.

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

@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

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.

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.

@tnokin thanks, I had to change your code a little to this in pm2libProcessContainer.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);
}

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.

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

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.

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

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

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 🤣

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rajendar38 picture rajendar38  Â·  3Comments

ghost picture ghost  Â·  3Comments

rangercyh picture rangercyh  Â·  4Comments

xzycn picture xzycn  Â·  3Comments

shaunwarman picture shaunwarman  Â·  3Comments