自动退出-NodeJS https Web服务器



要详细说明标题中的问题,

我用js制作了一个在节点服务器上运行的简单应用程序。我有一个拇指驱动器,里面有一个文件夹和一个start.bat文件。顾名思义,Start.bat将目录切换到我的服务器文件夹并启动服务器。Start.bat还启动另一个进程,以kiosk模式将边缘浏览器打开到localhost。当用户启动start.bat时,应用程序将出现在屏幕上,服务器在后台运行。当用户退出边缘浏览器时,他们需要在服务器cmd提示符下按CTRL+C来正确关闭服务器。

我需要一个在Edge浏览器关闭后自动关闭服务器的系统。我不确定是否有可能将关闭浏览器和节点服务器联系在一起,目前还没有找到在线解决方案。如果有人对可能解决我的问题有任何想法,我很乐意听到!

https-server.js

const https = require("https");
const path = require("path");
const fs = require("fs");
const ip = require("ip");
const process = require("process");
const app = express();
const port = 443;
process.chdir("..");
console.log("Current working dir: " + process.cwd());
var rootDir = process.cwd();
//determines what folder houses js, css, html, etc files
app.use(express.static(rootDir + "/public/"), function (req, res, next) {
const ip = req.ip;
console.log("Now serving ip:", "x1b[33m", ip, "x1b[37m");
next();
});
//determines which file is the index
app.get("/", function (req, res) {
res.sendFile(path.join(rootDir + "/public/index.html"));
});
var sslServer = https.createServer(
{
key: fs.readFileSync(path.join(rootDir, "certificate", "key.pem")),
cert: fs.readFileSync(path.join(rootDir, "certificate", "certificate.pem")),
},
app
);
//determines which port app (http server) should listen on
sslServer.listen(port, function () {
console.log(
"Server has successfully started, available on:",
"x1b[33m",
ip.address(),
"x1b[37m",
"listening on port:",
"x1b[33m",
+port,
"x1b[37m"
);
console.log("CTRL + C to exit server");
sslServer.close();
});

将提供任何需要的信息。

注册一个端点以退出进程

app.get('/shutdown', (req, res, next) => {
res.json({"message": "Received"});
next();
}, () => {
process.exit();
});

然后为onbeforeunload注册一个侦听器以向该端点发出请求。

let terminateCmdReceived = false;
async function shutdown(e) {
let response;
if (!terminateCmdReceived) {
e.preventDefault();
try {
response = await fetch('http://localhost:3000/shutdown');
const json = await response.json();
if(json.message === "Received") {
terminateCmdReceived = true; 
window.close();
}
} catch (e) {
console.error("Terminate Command was not received");    
}
}

}
window.onbeforeunload = shutdown

最新更新