-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
38 lines (36 loc) · 1.1 KB
/
index.js
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
// run `node index.js` in the terminal
const http = require('http');
const fs = require('fs');
const path = require('path');
http
.createServer(async (req, res) => {
if (req.url === '/') {
res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.end(fs.readFileSync('./index.html'));
} else {
try {
const content = fs.readFileSync(path.join(__dirname, req.url));
if (req.url.endsWith('.js')) {
res.setHeader('Content-Type', 'application/javascript');
} else if (req.url.endsWith('.html')) {
res.setHeader('Content-Type', 'text/html');
await delay(2000);
} else {
res.setHeader('Content-Type', 'text/css');
}
res.writeHead(200);
res.end(content);
} catch (error) {
res.setHeader('Content-Type', 'text/html');
res.writeHead(400);
res.end(
'<!doctype html><html><head></head><body><h1>Not found</h1></body></html>'
);
}
}
})
.listen(3000);
function delay(time) {
return new Promise((resolve) => setTimeout(resolve, time));
}