BlueGit

timfa filemanager

Files

filemanager / server / index.js

index.js

fixes and updates
timfa Tim Falken · pushed by timfa · 6 months ago
0ae63c84 History
index.js 1.7 KiB Download Raw
1'use strict';
2
3const express = require('express');
4const path = require('path');
5const { initDb, closeDb } = require('./db');
6const { ensureServerKeys } = require('./crypto');
7const { loadConfig } = require('./config');
8const authRoutes = require('./routes/auth');
9const filesRoutes = require('./routes/files');
10const adminRoutes = require('./routes/admin');
11
12const app = express();
13
14app.use(express.json({ limit: '50mb' }));
15app.use(express.static(path.join(__dirname, '../public')));
16
17app.use('/api/auth', authRoutes);
18app.use('/api/files', filesRoutes);
19app.use('/api/admin', adminRoutes);
20
21// SPA catch-all (only for non-API routes)
22app.get('*', (req, res) =>
23{
24 res.sendFile(path.join(__dirname, '../public/index.html'));
25});
26
27// Exposed so the shutdown route can trigger a graceful stop.
28function shutdown (server)
29{
30 if (!server || server.__isShuttingDown) return;
31 server.__isShuttingDown = true;
32
33 // Close DB first so file locks are released as early as possible.
34 closeDb();
35
36 server.close(() =>
37 {
38 process.exit(0);
39 });
40
41 // Force-exit after 5 s if connections don't drain in time.
42 setTimeout(() =>
43 {
44 process.exit(0);
45 }, 5000).unref();
46}
47
48function start ()
49{
50 initDb();
51 ensureServerKeys();
52
53 const config = loadConfig();
54 const port = config.port || 3000;
55
56 const server = app.listen(port, '0.0.0.0', () =>
57 {
58 console.log(`File manager running at http://localhost:${port}`);
59 });
60
61 // Give the admin route access to the server handle for graceful shutdown.
62 app.set('server', server);
63 app.set('shutdown', () => shutdown(server));
64
65 process.on('SIGINT', () => shutdown(server));
66 process.on('SIGTERM', () => shutdown(server));
67}
68
69try
70{
71 start();
72} catch (err)
73{
74 console.error('Failed to start server:', err);
75 process.exit(1);
76}