(_ => { require("dotenv").config(); const root_path = process.cwd(); const express = require("express"); const errorHandler = require('express-error-handler'); const path = require("path"); const http = require("http"); const middlewares = require(path.join(root_path, "src", "middlewares")); const _404 = require(path.join(root_path, "src", "middlewares", "404")); const _public = path.join(root_path, "public"); const _storage = path.join(root_path, "storage", "image"); const router = require(path.join(root_path, "src", "router")); const app = express(); app.set("view engine", "ejs"); // app.set("view cache", true); app.set("views", path.join(root_path, "resources", "views")); app.use(middlewares) app.use("/", express.static(_public)); app.use("/storage/image", express.static(_storage)); app.use("/", router); app.use(_404) app.use(errorHandler({ debug: true, log: true, })); // * 使用內建的 cluster 做管理 const cluster = require("cluster"); const os = require("os"); const cpus = os.cpus().length; if (cluster.isMaster && cpus.length > 1) { for (let i = 0; i < (cpus - 1); i++) { cluster.fork(); }; cluster.on("exit", (worker: any, code: any, signal: any) => { console.log(`Worker ${worker.process.pid} died with code: ${code}, and signal: ${signal}`); console.log('Starting a new worker'); cluster.fork(); }); const signals = ["SIGINT", "SIGTERM", "SIGHUP"]; signals.forEach(signal => { process.on(signal, () => { console.log(`Received ${signal}, shutting down master process...`); for (const id in cluster.workers) { console.log(`Killing worker ${cluster.workers[id].process.pid}`); cluster.workers[id].kill("SIGTERM"); } process.exit(0); }); }); } else { http.createServer(app).listen(process.env.HOST_PORT, () => { console.log(`========== [MODE ${process.env.ENV}] [PORT ${process.env.HOST_PORT}] ==========`); }); }; })();