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:
1/Users/sairamk/.pm2/logs/api-error-21.log last 15 lines:
221|api | /usr/local/Cellar/yarn/0.27.5_1/bin/yarn:2
321|api | PREFIX="/usr/local" exec "/usr/local/Cellar/yarn/0.27.5_1/libexec/bin/yarn.js" "$@"
421|api | ^^^^
521|api |
621|api | SyntaxError: Unexpected identifier
721|api | at createScript (vm.js:74:10)
821|api | at Object.runInThisContext (vm.js:116:10)
921|api | at Module._compile (module.js:533:28)
1021|api | at Object.Module._extensions..js (module.js:580:10)
1121|api | at Module.load (module.js:503:32)
1221|api | at tryModuleLoad (module.js:466:12)
1321|api | at Function.Module._load (module.js:458:3)
1421|api | at Object.<anonymous> (/usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js:70:21)
1521|api | at Module._compile (module.js:569:30)
1621|api | at Object.Module._extensions..js (module.js:580:10)
PM2 command that I use:
1pm2 start yarn --name api -- start
while npm start for the same, works fine with below command :
1pm2 start npm --name api -- start
Tried exploring many possibilities. What am I doing wrong ?
1
The error you’re getting is because a bash script (yarn) is being executed with node…
pm2’s default interpreter is set to node
.
To run yarn (bash script) correctly, you’ll have to set pm2’s interpreter to bash
:
shell
:
1pm2 start yarn --interpreter bash --name api -- start
or when you are using the ecosystem.config.js
:
1module.exports = {
2 apps : [{
3 name : 'yarn',
4 script : 'yarn',
5 args : 'start',
6 interpreter: '/bin/bash',
7 env: {
8 NODE_ENV: 'development'
9 }
10 }]
11};
Your yarn command is pointing to a bash script /usr/local/Cellar/yarn/0.27.5_1/bin/yarn
and not the yarn.js
in the same folder. By manually running something like
1pm2 start /usr/local/Cellar/yarn/0.27.5_1/bin/yarn.js --name api -- start
it should work as expected. Just adapt the path to the current location. In my case it was /usr/share/yarn/bin/yarn.js
.
As a sidenote: executing yarn like this takes up almost double the memory than compared to npm. I don’t know the exact reason, but I’ll stick to npm for pm2 since it should not make any difference, in theory…