You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
87 lines
2.5 KiB
87 lines
2.5 KiB
// 检查并释放被占用的端口
|
|
const { exec } = require('child_process');
|
|
const os = require('os');
|
|
|
|
// 要检查的端口
|
|
const PORT = 3001;
|
|
|
|
function killProcessOnPort(port) {
|
|
console.log(`开始检查端口 ${port} 的占用情况...`);
|
|
|
|
if (os.platform() === 'win32') {
|
|
// Windows系统
|
|
exec(`netstat -ano | findstr :${port}`, (error, stdout) => {
|
|
if (error) {
|
|
console.log(`端口 ${port} 未被占用`);
|
|
return;
|
|
}
|
|
|
|
const lines = stdout.trim().split('\n');
|
|
if (lines.length > 0) {
|
|
// 提取PID
|
|
const pid = lines[0].trim().split(/\s+/).pop();
|
|
console.log(`发现进程 ${pid} 占用端口 ${port}`);
|
|
|
|
// 杀死进程
|
|
exec(`taskkill /F /PID ${pid}`, (killError) => {
|
|
if (killError) {
|
|
console.error(`杀死进程 ${pid} 失败:`, killError.message);
|
|
} else {
|
|
console.log(`成功杀死进程 ${pid},端口 ${port} 已释放`);
|
|
}
|
|
});
|
|
} else {
|
|
console.log(`端口 ${port} 未被占用`);
|
|
}
|
|
});
|
|
} else {
|
|
// Linux/Mac系统
|
|
exec(`lsof -i :${port}`, (error, stdout) => {
|
|
if (error) {
|
|
console.log(`端口 ${port} 未被占用`);
|
|
return;
|
|
}
|
|
|
|
const lines = stdout.trim().split('\n');
|
|
if (lines.length > 1) {
|
|
// 提取PID
|
|
const pid = lines[1].trim().split(/\s+/)[1];
|
|
console.log(`发现进程 ${pid} 占用端口 ${port}`);
|
|
|
|
// 杀死进程
|
|
exec(`kill -9 ${pid}`, (killError) => {
|
|
if (killError) {
|
|
console.error(`杀死进程 ${pid} 失败:`, killError.message);
|
|
} else {
|
|
console.log(`成功杀死进程 ${pid},端口 ${port} 已释放`);
|
|
}
|
|
});
|
|
} else {
|
|
console.log(`端口 ${port} 未被占用`);
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
// 执行端口检查和释放
|
|
killProcessOnPort(PORT);
|
|
|
|
// 延迟2秒后再次启动服务器(如果是Windows系统)
|
|
setTimeout(() => {
|
|
if (os.platform() === 'win32') {
|
|
console.log('\n正在尝试重新启动服务器...');
|
|
const serverProcess = exec('node server-mysql.js');
|
|
|
|
serverProcess.stdout.on('data', (data) => {
|
|
console.log(`服务器输出: ${data}`);
|
|
});
|
|
|
|
serverProcess.stderr.on('data', (data) => {
|
|
console.error(`服务器错误: ${data}`);
|
|
});
|
|
|
|
serverProcess.on('close', (code) => {
|
|
console.log(`服务器进程退出,代码: ${code}`);
|
|
});
|
|
}
|
|
}, 2000);
|