-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
82 lines (72 loc) · 1.94 KB
/
server.js
File metadata and controls
82 lines (72 loc) · 1.94 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const http = require("http");
const fs = require("fs");
const path = require("path");
// Définir une liste de chemins dans lesquels chercher les fichiers
const possiblePaths = [
path.join(__dirname, "./todo-app/public"),
path.join(__dirname, "./todo-app/public/js"),
path.join(__dirname, "./todo-app"),
path.join(__dirname, "."),
];
const server = http.createServer((req, res) => {
let fileFound = false;
// Itérer sur chaque chemin possible
for (const basePath of possiblePaths) {
let filePath = path.join(
basePath,
req.url === "/" ? "index.html" : req.url
);
if (fs.existsSync(filePath)) {
fileFound = true;
serveFile(filePath, res);
break;
}
}
// Si le fichier n'a pas été trouvé, renvoyer index.html par défaut
if (!fileFound) {
const fallbackFilePath = path.join(
__dirname,
"./todo-app/public",
"index.html"
);
serveFile(fallbackFilePath, res);
}
});
function serveFile(filePath, res) {
fs.readFile(filePath, (err, content) => {
if (err) {
res.writeHead(500);
res.end("Erreur du serveur: " + err.code);
return;
}
const extname = path.extname(filePath);
let contentType = "text/html"; // Par défaut
switch (extname) {
case ".js":
contentType = "application/javascript";
break;
case ".css":
contentType = "text/css";
break;
case ".json":
contentType = "application/json";
break;
case ".png":
contentType = "image/png";
break;
case ".jpg":
contentType = "image/jpg";
break;
case ".ico":
contentType = "image/x-icon";
break;
// Ajouter d'autres types MIME si nécessaire
}
res.writeHead(200, { "Content-Type": contentType });
res.end(content, "utf-8");
});
}
const PORT = 3001;
server.listen(PORT, () => {
console.log(`Le serveur écoute sur http://localhost:${PORT}`);
});