-
Notifications
You must be signed in to change notification settings - Fork 5
/
http-stream.js
43 lines (33 loc) · 1.09 KB
/
http-stream.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
39
40
41
42
43
const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
const srvUrl = url.parse(`http://${req.url}`);
let pathname = srvUrl.pathname;
if(pathname === '/') pathname = '/index';
const pathInfo = path.parse(pathname);
if(!pathInfo.ext) {
pathInfo.ext = '.html';
pathInfo.base += pathInfo.ext;
}
const resPath = path.join('resource', pathInfo.dir, pathInfo.base);
if(!fs.existsSync(resPath)) {
res.writeHead(404, {'Content-Type': 'text/html'});
return res.end('<h1>404 Not Found</h1>');
}
const resStream = fs.createReadStream(resPath);
if(pathInfo.ext === '.html' || pathInfo.ext === '.htm') {
res.writeHead(200, {'Content-Type': 'text/html'});
} else if(pathInfo.ext === '.png') {
res.writeHead(200, {'Content-Type': 'image/png'});
}
// ...
resStream.pipe(res);
});
server.on('clientError', (err, socket) => {
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
server.listen(10080, () => {
console.log('opened server on', server.address());
});