-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserve.js
More file actions
42 lines (35 loc) · 1.27 KB
/
Copy pathserve.js
File metadata and controls
42 lines (35 loc) · 1.27 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
import http from 'http';
import fs from 'fs';
import path from 'path';
const port = process.env.PORT || 3000;
const root = process.cwd();
const contentType = (filePath) => {
if (filePath.endsWith('.html')) return 'text/html';
if (filePath.endsWith('.js')) return 'application/javascript';
if (filePath.endsWith('.css')) return 'text/css';
if (filePath.endsWith('.json')) return 'application/json';
return 'text/plain';
};
const server = http.createServer((req, res) => {
let reqPath = decodeURI(req.url.split('?')[0]);
if (reqPath === '/') reqPath = '/index.html';
const filePath = path.join(root, reqPath);
fs.stat(filePath, (err, stats) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not found');
return;
}
if (stats.isDirectory()) {
res.writeHead(200, { 'Content-Type': 'text/html' });
const files = fs.readdirSync(filePath).map(f => `<li><a href="${path.join(reqPath, f)}">${f}</a></li>`).join('\n');
res.end(`<h1>Index of ${reqPath}</h1><ul>${files}</ul>`);
return;
}
fs.createReadStream(filePath).pipe(res);
res.writeHead(200, { 'Content-Type': contentType(filePath) });
});
});
server.listen(port, () => {
console.log(`Serving ${root} at http://localhost:${port}`);
});