How to stop npm script in background automatically

I use npm scripts, I have some of them that should run in parallel. I have something like this:

... scripts: { "a": "taskA &", "preb": "npm run a", "b": "taskB" } ... 

It's fine! But I would like to kill automatically taskA by running the background after taskB completes.

How can i do this? Thanks!

+6
source share
2 answers

I do not believe npm is the best tool for managing complex relationships between processes.

You will be much better off serving the creation of a node script that uses the node child_process module to control the start and kill of shared processes, possibly using spawn .

Having said this and in the spirit of always trying to provide a direct, useful answer.

You can structure your npm scripts, for example (assuming a bash shell):

 scripts:{ runBoth: "npm runA & npm runB", // run tasks A and B in parallel runA: "taskA & TASKA_PID=$!", // run task A and capture its PID into $TASKA_PID runB: "taskB && kill $TASKA_PID" // run task B and if it completes successfully, kill task A using its saved PID } 

The only β€œmagic” here is this:

+14
source

The npm-run-all package might be what you are looking for:

 $ npm install --save npm-run-all 

Then in your package.json file:

 "scripts": { "runA": "taskA", "runB": "taskB", "runBoth": "npm-run-all -p runA runB" } 

( -p runs them in parallel, use -s for sequential ones.)

0
source

Source: https://habr.com/ru/post/980622/


All Articles