-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
77 lines (67 loc) · 2.05 KB
/
server.js
File metadata and controls
77 lines (67 loc) · 2.05 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Require modules
let http = require('http');
let url = require('url');
let path = require('path');
let fs = require('fs');
let UAParser = require('ua-parser-js');
let parser = new UAParser();
// Array of mime types
let mimeTypes = {
"html": "text/html",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"png": "image/png",
"js": "text/javascript",
"css": "text/css"
};
// Create server
http.createServer(function (req, res) {
let uri = url.parse(req.url).pathname;
let fileName = path.join(process.cwd(), decodeURI(uri));
console.log('Loading ' + uri);
let stats;
try {
stats = fs.lstatSync(fileName);
} catch (e) {
res.writeHead(404, {
'Content-Type': 'text/plain'
});
res.write('404 Not found');
res.end();
return;
}
let ip = req.headers['x-forwarded-for'] || req.connection.address();
console.log('----------- Request Info -----------');
console.log('http ', req.httpVersion);
console.log('method', req.method);
console.log('ip', ip);
console.log('headers', req.headers);
console.log(parser.setUA(req.headers['user-agent']).getResult());
console.log('----------- ------------ -----------');
// Check if file/directory
if (stats.isFile()) {
let mimeType = mimeTypes[path.extname(fileName).split('.')
.reverse()[0]];
res.writeHead(200, {
'Content-Type': mimeType
});
let fileStream = fs.createReadStream(fileName);
fileStream.pipe(res);
} else if (stats.isDirectory()) {
res.writeHead(302, {
'Location': 'index.html'
});
res.end();
} else {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.write('500 Internal error');
res.end();
}
}).listen(1337, '0.0.0.0');
/*
* http.createServer(function (req, res){ res.writeHead(200, {'Content-type':
* 'text/plain'}); res.end('Hello world!'); }).listen(1337, '127.0.0.1');
*/
console.info('Server runing at http://localhost:1337');