-
Notifications
You must be signed in to change notification settings - Fork 410
Expand file tree
/
Copy pathcreateServer.js
More file actions
49 lines (37 loc) · 1.09 KB
/
createServer.js
File metadata and controls
49 lines (37 loc) · 1.09 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
'use strict';
const http = require('http');
const fs = require('fs');
function createServer() {
return http.createServer((req, res) => {
const normalizedUrl = new URL(req.url, `http://${req.headers.host}`);
const { pathname } = normalizedUrl;
if (pathname.includes('//')) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('File Not Found');
return;
}
if (!pathname.startsWith('/file')) {
res.writeHead(400, { 'Content-Type': 'text/plain' });
res.end('Should be /file/*');
return;
}
const relativeFilePath = pathname.replace(/^\/file\/?/, '');
if (!relativeFilePath) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('File Not Found');
return;
}
fs.readFile(`public/${relativeFilePath}`, (err, data) => {
if (err) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('File Not Found');
return;
}
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(data);
});
});
}
module.exports = {
createServer,
};