js
const { spawn } = require("child_process");
const { app, shell, dialog } = require("electron");
let server;
let powershellProcess;
let isExiting = false;
function startPowerShell() {
try {
const command = [
"[Console]::OutputEncoding = [System.Text.Encoding]::UTF8",
"[Console]::InputEncoding = [System.Text.Encoding]::UTF8",
'[Console]::WriteLine("==================== 应用状态 ====================")',
'[Console]::WriteLine("本地服务器已启动:http://localhost:3000")',
'[Console]::WriteLine("提示:关闭此窗口将终止应用程序")',
'[Console]::WriteLine("===================================================")',
'[Console]::WriteLine("按任意键关闭应用...")',
'$host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") | Out-Null',
"exit",
].join("; ");
// 使用更简单直接的方式启动PowerShell
powershellProcess = spawn(
"powershell.exe",
["-NoProfile", "-Command", command],
{
stdio: "inherit",
detached: false,
windowsHide: false,
}
);
// 处理PowerShell进程退出
powershellProcess.on("exit", (code) => {
if (!isExiting) {
// 用户主动关闭了PowerShell窗口
app.quit();
}
});
// 处理启动错误
powershellProcess.on("error", (err) => {
console.error("启动PowerShell失败:", err);
dialog.showErrorBox(
"启动失败",
`无法启动PowerShell:${err.message}\n请确认系统已安装PowerShell`
);
cleanupResources();
app.quit();
});
} catch (err) {
dialog.showErrorBox("启动异常", err.message);
cleanupResources();
app.quit();
}
}
function cleanupResources() {
if (isExiting) return;
isExiting = true;
if (server) {
server.close();
}
if (powershellProcess && !powershellProcess.killed) {
powershellProcess.kill();
}
}
app.whenReady().then(() => {
startPowerShell();
startLocalServer();
});
为什么打开window的powershell无法显示任何文字,这是在electron的主进程启动的