Files
throttle_motor_mapping/server.js
T
2025-06-12 11:15:28 +02:00

86 lines
2.2 KiB
JavaScript

const express = require("express");
const path = require("path");
const fileUpload = require("express-fileupload");
const basicAuth = require("express-basic-auth");
const fs = require("fs");
const app_conf = require("./app/config/app.conf.js");
const public_routes = require('./app/routes/public_routes');
const private_routes = require('./app/routes/private_routes');
const logger = require("./app/utils/logger.util.js");
const map_socket = require("./app/utils/socket.util.js");
const app = express();
var shutting_down = false;
/*
* Static middleware - serve css and js files to public
*/
app.use(express.json());
// Set temp directory and upload size limit
app.use(fileUpload({
limits: { fileSize: 102400 },
useTempFiles: true,
tempFileDir: path.join(__dirname, app_conf.temp_directory)
}));
app.use("/", public_routes);
app.use(`${app_conf.app_url}`, basicAuth({
users: {
[app_conf.username]: app_conf.password
},
challenge: true
}), private_routes);
/*
* Initialise ExpressJS
* Using ejs to pass variables from ExpressJS to HTML pages.
*/
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, app_conf.views_directory));
const server = app.listen(app_conf.port, (error) => {
logger.info(`Starting ${app_conf.name} ${app_conf.program}.`);
fs.rm(path.join(__dirname, app_conf.temp_directory, "/."), { recursive: true }, (error) => {
if (error == null) {
logger.info("Removed temp directory.");
} else if (error.code === "ENOENT") {
logger.info("Temp directory not found.");
} else {
logger.error(error.message);
}
});
if (error) {
logger.error(error.message);
shutdown();
} else {
logger.info(`Listening to port ${app_conf.port}.`);
}
})
/*
* Handle Ctrl+C to shutdown gracefully
*/
process.on("SIGINT", () => {
if (shutting_down) {
logger.emerg("Shutting down forcefully.");
process.exit(-1);
} else {
shutdown();
}
});
/*
* This function shuts the server down
*/
function shutdown() {
shutting_down = true;
map_socket.closeSocket();
server.close(() => {
logger.info("Shutting down server.");
});
}