如何杀死npm子进程

时间:2017-12-28 17:18:12

标签: javascript node.js npm kill child-process

我在package.json上定义了debug脚本。此脚本将启动node应用。

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

所以当我spawn npm run debug并且我杀了它时,node进程就不会被杀死。

我尝试使用child_process.kill杀死整个过程并生成kill bash命令而没有运气,因为pid并不属于{ {1}}使用node启动。

如何杀死我不拥有npm run debug的{​​{1}}进程?

1 个答案:

答案 0 :(得分:0)

您不必拥有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);
相关问题