I am trying to execute shell script via spawnSync where I need to run one of commands in background but the "&" seems just to be ignored.
My code:
spawnSync(`echo "*** Begin" && npm run startServer & echo "*** End"`, {
stdio: ["ignore", "pipe", "inherit"],
encoding: "utf-8",
shell: true,
});
From some reason, the command startServer is not executed in the background so second echo command is never executed.
Note: The script above is running as expected when I run it directly from bash.
EDIT: A little bit of clarification:
- The command
startServerwill run forever as it is serving the server so it will never return under normal circumstances. From that reason, I need to run in background. - Originally, I had standard shell script (see below) which was working as expected. I thought that I will be able to execute more/less same script with
spawnSyncbut it behaves differently.
some commands
some commands
npm run startServer &
some commands
....
I'm not sure about the specifics of nodeJS and spawnSync, howver you essentially want to disassociate your server command from the current shell process.
You can achieve this by prepending your npm command with
nohupSince you're attempting to run the echo End command in parallel with your npm command, it will execute the end command right after the Begin. Further, it will keep the command running even after the terminal is killed.