通过 nodejs 子进程方式获取 被占用端口的 pid 和应用名称,同时区分环境 windows 和 mac
提供给用户,pId 和 pName 让用户自己决定是 kill 进程 还是 提示使用者什么应用占用了端口
const { execSync } = window.require('child_process');
const os = window.require('os');
const platform = os.platform();
const GetProcessInfo = (port) =>
new Promise((resolve, reject) => {
if (platform === 'win32') {
const order = `netstat -aon | findstr ${port}`;
try {
const stdout = execSync(order);
const portInfo = stdout.toString().trim().split(/\s+/);
const pId = portInfo[portInfo.length - 1];
const processStdout = execSync(`tasklist | findstr ${pId}`);
const [pName] = processStdout.toString().trim().split(/\s+/);
resolve({
pId,
pName,
});
} catch (error) {
reject(error);
}
} else {
const order = `lsof -i :${port}`;
try {
const stdout = execSync(order);
const [pName, pId] = stdout
.toString()
.trim()
.split(/\n/)[1]
.split(/\s+/);
resolve({
pId,
pName,
});
} catch (error) {
reject(error);
}
}
});
module.exports = GetProcessInfo;