如何自动停止在后台运行的npm脚本 [英] How to stop npm script running in background automatically

查看:774
本文介绍了如何自动停止在后台运行的npm脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用npm脚本,我有一些应该并行运行。我有这样的事情:

Im using npm scripts, I have some of them that should run in parallel. I've got something like this:

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

这很好!但是我想在taskB完成后自动杀死taskA运行后台。

This is fine! But I'd like to kill automatically taskA running the background after taskB has finished.

我该怎么做?
谢谢!

How can I do that? Thanks!

推荐答案

我不相信npm是管理流程之间复杂关系的最佳工具。

I don't believe npm is the best tool to manage complex relationships between processes.

创建一个使用节点的节点脚本 child_process 模块,用于管理协同进程的启动和终止,可能使用 spawn

You would be far better served by creating a node script that uses node's child_process module to manage the launching and killing of co-processes, perhaps using spawn.

话虽如此,本着一贯努力提供直接,有用的答案的精神。

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

你可以构建你的npm脚本,如(假设 bash shell ):

You could structure your npm scripts like (assumes 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
}

这里唯一的'魔法'是:


  1. 当你运行命令时使用 bash shell的背景(当你将& 添加到最后时会发生这种情况),你可以发现它使用 $!进行PID,但仅在命令运行后立即执行。(参见高级Bash-Scripting指南:第9章。对变量的另一种看法 - 9.1。内部变量的描述。)

  2. taskB 必须在成功时调用process.exit(0)或在失败时调用process.exit(-1),以便&& 测试是处理正确。(有关更多信息,请参阅此答案离开。)

  1. when you run a command in the background using the bash shell (which is what happens when you add & to the end), you can discover it PID using $!, but only immediately after the command is run. (See Advanced Bash-Scripting Guide: Chapter 9. Another Look at Variables - 9.1. Internal Variables for its description.)
  2. taskB must call process.exit(0) on success or process.exit(-1) on failure so that the && test is handled correctly. (See this answer for more information.)

这篇关于如何自动停止在后台运行的npm脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆