-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
60 lines (50 loc) · 1.48 KB
/
Copy pathserver.js
File metadata and controls
60 lines (50 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const polka = require('polka');
const serve = require('serve-static');
const path = require('path');
const fs = require('fs');
const send = require('send');
let servers = [];
function createSiteServer({ name, port, directory }) {
const sitePath = path.resolve(__dirname, directory);
const app = polka();
app.use(serve(sitePath, {
extensions: ['html'],
}));
app.get('*', (req, res) => {
const indexPath = path.join(sitePath, 'index.html');
fs.readFile(indexPath, (err, data) => {
if (err) {
console.error(`❌ Erreur pour le site "${name}" :`, err.message);
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end(`Erreur serveur (${name}) : ${err.message}`);
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
}
});
});
const server = app.listen(port, () => {
console.log(`✅ Site "${name}" lancé sur http://localhost:${port}`);
});
return server.server;
}
function startServers() {
stopServers();
const config = JSON.parse(fs.readFileSync('./cfg/sites.json', 'utf-8'));
servers = config.map(createSiteServer);
}
function stopServers() {
servers.forEach(server => {
try {
server.close();
} catch (err) {
console.warn('Erreur lors de la fermeture du serveur :', err.message);
}
});
servers = [];
}
startServers();
fs.watchFile('./cfg/sites.json', () => {
console.log('🔁 Config modifiée. Rechargement des sites...');
startServers();
});