Using pm2 to do yarn start gives error while npm start works fine

Sairam Krish picture Sairam Krish · Aug 25, 2017 · Viewed 8.6k times · Source

I have a NodeJs microservice. Doing yarn start normally works perfectly fine. When I try to use pm2 to start this as a background service, facing the below issue:

/Users/sairamk/.pm2/logs/api-error-21.log last 15 lines:
21|api     | /usr/local/Cellar/yarn/0.27.5_1/bin/yarn:2
21|api     | PREFIX="/usr/local" exec "/usr/local/Cellar/yarn/0.27.5_1/libexec/bin/yarn.js" "$@"
21|api     |                     ^^^^
21|api     |
21|api     | SyntaxError: Unexpected identifier
21|api     |     at createScript (vm.js:74:10)
21|api     |     at Object.runInThisContext (vm.js:116:10)
21|api     |     at Module._compile (module.js:533:28)
21|api     |     at Object.Module._extensions..js (module.js:580:10)
21|api     |     at Module.load (module.js:503:32)
21|api     |     at tryModuleLoad (module.js:466:12)
21|api     |     at Function.Module._load (module.js:458:3)
21|api     |     at Object.<anonymous> (/usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js:70:21)
21|api     |     at Module._compile (module.js:569:30)
21|api     |     at Object.Module._extensions..js (module.js:580:10)

PM2 command that I use:

pm2 start yarn --name api -- start

while npm start for the same, works fine with below command :

pm2 start npm --name api -- start

Tried exploring many possibilities. What am I doing wrong ?

Answer

chimurai picture chimurai · Aug 17, 2018

The error you're getting is because a bash script (yarn) is being executed with node...

Because pm2's default interpreter is set to node.

To run yarn you'll have to set the interpreter to bash:

shell:

pm2 start yarn --interpreter bash --name api -- start

or when you are using the ecosystem.config.js:

module.exports = {
  apps : [{
    name      : 'yarn',
    script    : 'yarn',
    args      : 'start',
    interpreter: '/bin/bash',
    env: {
      NODE_ENV: 'development'
    }
  }]
};