[英]Node.js get pid at port
In Node.js, I want to kill a server running on port 1337
. 在Node.js中,我想杀死在端口
1337
上运行的服务器。 process.kill(pid)
seems like the way to do that. process.kill(pid)
似乎是这样做的方法。 But how do I get the pid of the server running on port 1337
, in Node.js? 但是,如何在Node.js中获取在端口
1337
上运行的服务器的pid?
I see plenty of examples of how to do this with ps
and lsof
. 我看到了很多关于如何使用
ps
和lsof
进行此操作的示例。 Is there a way to pull this off without relying on shell commands in Node.js? 有没有办法在不依赖Node.js中的Shell命令的情况下实现这一目标?
Here is how I would do this by relying on lsof
: 这是我依靠
lsof
来做到这一点的方法:
Number(child_process.execSync('lsof -i :1337 -t'))
If you launched the server as a child from another nodejs process, you can just do child.pid
to get the pid of the server process. 如果您以另一个Node.js进程的子进程启动服务器,则只需执行
child.pid
即可获取服务器进程的pid。
Example: 例:
var child = child_process.spawnSync(command[, args][, options]);
console.log(child.pid);
process.kill(child.pid);
To answer my question, I can determine the pid(s) at a port with the port-pid
package: https://www.npmjs.com/package/port-pid 要回答我的问题,我可以使用
port-pid
软件包确定port-pid
: https : //www.npmjs.com/package/port-pid
However, to solve my problem, I instead adopted the philosophy that there was a "good reason" the port was in use, and instead opted to kill the child process from where it was spawned by wrapping require('child_process').spawn
: 但是,为了解决我的问题,我改而采用了端口正在使用的“充分理由”的哲学,而是选择通过包装
require('child_process').spawn
杀死从其产生的子进程require('child_process').spawn
var childProcess = require('child_process');
var spawn = (function () {
var children = [];
process.on('exit', function () {
children.forEach(function (child) {
child.kill();
});
});
return function () {
var child = childProcess.spawn.apply(childProcess, arguments);
children.push(child);
return child;
};
}());
spawn('node', ['server/server.js'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.