BlueGit

timfa filemanager

Files

filemanager / server / index.js

index.js

import project
timfa Tim Falken · pushed by timfa · 6 months ago
d3c0b911 History
index.js 1.5 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 res.sendFile(path.join(__dirname, '../public/index.html'));
24});
25
26// Exposed so the shutdown route can trigger a graceful stop.
27function shutdown(server) {
28 server.close(() => {
29 closeDb();
30 process.exit(0);
31 });
32 // Force-exit after 5 s if connections don't drain in time.
33 setTimeout(() => {
34 closeDb();
35 process.exit(0);
36 }, 5000).unref();
37}
38
39function start() {
40 initDb();
41 ensureServerKeys();
42
43 const config = loadConfig();
44 const port = config.port || 3000;
45
46 const server = app.listen(port, '0.0.0.0', () => {
47 console.log(`File manager running at http://localhost:${port}`);
48 });
49
50 // Give the admin route access to the server handle for graceful shutdown.
51 app.set('server', server);
52 app.set('shutdown', () => shutdown(server));
53}
54
55try {
56 start();
57} catch (err) {
58 console.error('Failed to start server:', err);
59 process.exit(1);
60}