如何杀死一个 npm 子进程

How to kill a npm child process

我有一个 package.json,我在上面定义了一个 debug 脚本。此脚本启动 node 应用程序。

整个 npm 脚本正在由测试启动,一旦测试结束,最后一个必须终止 debug 脚本。

所以当我 spawn npm run debug 并杀死它时,node 进程没有被杀死。

我试图用 child_process.kill 终止整个进程并生成 kill bash 命令但没有成功,因为 pid 不属于node 使用 npm run debug.

启动

如何终止我不拥有其 pidnode 进程?

您不一定要拥有 PID 才能杀死它(只要用户 运行 脚本有权执行此操作)。

您可以生成命令并像在命令行中那样执行操作(有多种方法)。还有像 find-process 这样的包,你也可以用它来找到进程。

一个更简单的方法是在 debug 启动时写入一些包含 pid 的文件(如果可以的话)。然后你可以读回那个文件来获取 PID。

// in debug
import { writeFile } from 'fs';

writeFile('debug.pid', process.pid, 'utf8', err => err && console.log('Error writing pid file'));

// in app where it'll kill
import { readFile } from 'fs';

let debugPid;
readFile('debug.pid', 'utf8', (err, data) => err ? console.log('Error reading pid file') : debugPid = data);

无论采用何种方法,一旦获得 PID,请使用 process.kill() 将其杀死:

process.kill(pid);