如何从 nodejs 中终止 windows 上的 运行 进程

How to kill a running process on windows from nodejs

我想通过 nodejs 在 windows 上关闭 chrome 应用程序。

这是我所做的:

var ps = require('ps-node');
ps.lookup({ pid: 8092 }, function(err, resultList ) {
if (err) {
    throw new Error( err );
}

var process = resultList[ 0 ];

if( process ){

    console.log( 'PID: %s, COMMAND: %s, ARGUMENTS: %s', process.pid, process.command, process.arguments );
//process.kill(8092)
}
else {
    console.log( 'No such process found!' );
}

});

我无法终止进程。任何人都可以建议一种方法来做到这一点。 我试过 process.exit() process.kill process.abort,但对我没有任何用处。如果你能帮帮我就太好了。

只需使用ps.kill

ps.kill('8092', function( err ) {
    if (err) {
        throw new Error( err );
    }
    else {
        console.log( 'Process with pid 8092 has been killed!');
    }
});

您可以查看 documentation 了解更多信息

那个调用有一个 npm 包 taskkill

const taskkill = require('taskkill');

const input = [4970, 4512];

taskkill(input).then(() => {
    console.log(`Successfully terminated ${input.join(', ')}`);
});

或者您可以查看那个包并复制相关代码。

您可以使用 child_process.exec() to call taskkill. The below snippet uses the taskkill 命令并使用 PID 或 exe 文件名终止进程。

const {exec} = require('child_process')

const pid = 8092

// example app name 
const appName = 'firefox.exe' 

// Kills a PID and all child process
exec(`taskkill /pid ${pid} /t`, (err, stdout, stderr) => {
    if (err) {
      throw err
    }

    console.log('stdout', stdout)
    console.log('stderr', err)
  })
})

// Kills a process based on filename of the exe and all child processes
exec(`taskkill /im ${appName} /t`, (err, stdout, stderr) => {
    if (err) {
      throw err
    }

    console.log('stdout', stdout)
    console.log('stderr', err)
  })
})

试试这个,这是一个名为 tree-kill 的 npm 包。它会有效地终止进程。

var kill  = require('tree-kill');
const spawn = require('child_process').spawn;

var scriptArgs = ['myScript.sh', 'arg1', 'arg2', 'youGetThePoint'];
var child = spawn('sh', scriptArgs);

// some code to identify when you want to kill the process. Could be
// a button on the client-side??
button.on('someEvent', function(){
    // where the killing happens
    kill(child.pid);
});