'PM2 Error: Cannot find module when using ecosystem file

I'm having an issue with pm2.

If I start my app with

cd /my/path
pm2 start server.js

everything works correctly, but if I use an ecosystem.config.js file, then it gives the following error

pm2 start ecosystem.config.js
Error: Cannot find module '/my/path/server.js'\n    at Function.Module._resolveFilename

my ecosystem file is configured as follows

module.exports = {
    "apps": [{
        "name": "MyApp",
        "script": "server.js",
        "cwd": "/my/path" 
    }]
}

I tried uninstalling pm2, updating npm and reinstalling node_modules, but still I can't understand why it says a module is missing in my file (expecially because it works when not using the ecosystem file)



Solution 1:[1]

Ensure that the ecosystem.config.js is in the root of your project as well as your server entry file (server.js) and specify your script as below:

module.exports = {
    "apps": [{
        "name": "MyApp",
        "script": "./server.js"
    }]
}

Solution 2:[2]

Reading from https://pm2.keymetrics.io/docs/usage/application-declaration/

Field   Type        Example         Description
name    (string)    “my-api”        application name (default to script filename without extension)
script  (string)    ”./api/app.js”  script path relative to pm2 start
cwd     (string)    “/var/www/”     the directory from which your app will be launched

I would try:

  • with "script": "./server.js" (kind of strange, I know)
  • remove the cwd parameter and setting ./my/path/server.js

Solution 3:[3]

Try this command: pm2 start src/server.js

or other folder name before server file name

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Tyler2P