-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
63 lines (52 loc) · 1.61 KB
/
Copy pathserver.js
File metadata and controls
63 lines (52 loc) · 1.61 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
#!/usr/bin/env node
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = process.env.PORT || 3000;
const BASE_DIR = __dirname;
const INDEX_PATH = path.join(BASE_DIR, 'index.html');
const server = http.createServer((req, res) => {
const { url, method } = req;
if (method !== 'GET' && method !== 'HEAD') {
res.writeHead(405, { 'Content-Type': 'text/plain' });
res.end('Method Not Allowed');
return;
}
const requestedPath = url === '/' ? INDEX_PATH : path.join(BASE_DIR, url);
fs.stat(requestedPath, (statErr, stats) => {
if (statErr || !stats.isFile()) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
return;
}
const ext = path.extname(requestedPath).toLowerCase();
const contentType = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif'
}[ext] || 'application/octet-stream';
const headers = {
'Content-Type': contentType,
'Content-Length': stats.size,
'Cache-Control': 'no-cache'
};
res.writeHead(200, headers);
if (method === 'HEAD') {
res.end();
return;
}
const fileStream = fs.createReadStream(requestedPath);
fileStream.pipe(res);
fileStream.on('error', () => {
res.destroy();
});
});
});
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});