首页 > 解决方案 > 如何在电子中创建和管理 npm 进程

问题描述

我正在尝试制作这个小的 QoL 应用程序,它可以在我扔给它的任何项目(反应、聚合物等)的 package.json 中触发我的脚本。

到目前为止,它可以正常工作。至少在我终止应用程序或想要终止特定进程之前(例如在控制台中运行 npm start 时使用 ctrl+c )。

我目前正在以这种方式调用命令:

const exec = require("child_process").execFile;
...
let ps = exec("command.bat", [path, command], (error, stdout, stderr)=>{}) //command.bat contains only: cd "%1" \n npm "%2"

以前我像这样使用node-powershell

const Shell = require('node-powershell');
...
let sh = new Shell();
sh.addCommand(`cd ${fs.realpathSync(path)}`);
sh.addCommand(`npm ${command}`);
sh.invoke();

而且我已经尝试使用ps-tree希望这将列出由我的进程启动的所有进程,以便我可以杀死它们但没有运气,并且因为它创建了额外的一两个进程,所以它很快就会失控。

const cp = require('child_process');
...
psTree(ps.pid, function (err, children) {
    cp.spawn('kill', ['-9'].concat(children.map(function (p) { return p.PID })));
});

因此,如果有一些解决方案,我将不胜感激。如果有的话,我也愿意接受任何不同的解决方案。

提前致谢。

标签: node.jsprocesselectron

解决方案


推荐阅读