-
Notifications
You must be signed in to change notification settings - Fork 146
/
Copy pathserver.js
49 lines (39 loc) · 1.18 KB
/
server.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
44
45
46
47
48
49
const http = require('http');
const url = require('url');
const fs = require('fs');
const mimes = {
css : 'text/css',
html : 'text/html',
js : 'application/javascript'
};
const paths = {
css : '.',
html : '.',
js : '../../sdk/web'
};
function zeroPad(num) {
return num < 10 ? '0' + num : num;
}
function timeStamp() {
const d = new Date();
return `${zeroPad(d.getMonth() + 1)}-${zeroPad(d.getDate())} ` +
`${zeroPad(d.getHours())}:${zeroPad(d.getMinutes())}:${zeroPad(d.getSeconds())}`;
}
http.createServer((req, res) => {
const parsed = url.parse(req.url);
const fileName = parsed.pathname === '/' ? '/index.html' : parsed.pathname;
const fileType = fileName.split('.').slice(-1)[0];
const fullPath = ((fileName === '/main.js') ? '.' : (paths[fileType] || '.')) + fileName;
let code = 404;
let color = '\x1b[31m';
let body = '404';
if (fs.existsSync(fullPath)) {
code = 200;
color = '\x1b[32m';
body = fs.readFileSync(fullPath);
}
console.log(`${color}%s\x1b[0m %s`, code, `[${timeStamp()}] ${fullPath}`);
res.writeHead(code, {'Content-Type': mimes[fileType] || 'text/plain'});
res.end(body);
}).listen(9000);
console.log('Development server started on port 9000');