自动退出 - NodeJS https 网络服务器

Automatic exit - NodeJS https webserver

针对标题中的问题进行详细说明,

我用 js 做了一个简单的应用程序,运行在节点服务器上。我有一个拇指驱动器,其中包含一个文件夹和一个 start.bat 文件。 Start.bat,顾名思义,将目录切换到我的服务器文件夹,启动服务器。 Start.bat 还会启动另一个进程,以 kiosk 模式将边缘浏览器打开到本地主机。当用户启动 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