【发布时间】:2021-05-26 20:40:14
【问题描述】:
为了详细说明标题中的问题,
我用 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();
});
将提供任何需要的信息。
【问题讨论】:
-
您可以向服务器发出请求以将其关闭。参考[
window.onbeforeonload事件](stackoverflow.com/questions/13443503/…) -
@Oluwafemi Sule 是的,我的 index.html 脚本文件上有一个 windows.onbeforeonload 事件。它目前所做的只是 console.log("Browser closed")。您能否详细说明我如何使用它来请求关闭服务器?