-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
74 lines (65 loc) · 2.14 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
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
const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
console.log('服务已启动,端口4001')
});
server.on('request', (req, res) => {
let {pathname} = url.parse(req.url);
console.log(pathname)
if ( pathname === '' || pathname === '/' ) {
res.writeHead(200, 'ok', {
'Content-Type': 'text/html'
})
try {
let indexHtml = fs.readFileSync(String(path.join(__dirname, '/src/template/index.html')));
res.end(indexHtml);
} catch(e) {
res.end(e);
}
}
if ( /\/api\/selec/.test(pathname) ) {
let returnData = {};
try {
let json = new Buffer(JSON.parse(JSON.stringify(fs.readFileSync(path.join(__dirname, '/src/api/select.json')))));
returnData.status = 1;
returnData.value = JSON.parse(json.toString());
res.writeHead(200, 'ok', {
'Content-type': 'application/json'
});
res.end(JSON.stringify(returnData));
} catch(e) {
res.writeHead(500, 'error');
res.end();
}
}
if ( /^\/public\//.test(pathname) ) {
let filePath = path.join(__dirname, '/src/', pathname);
try {
fs.accessSync(filePath, fs.R_OK | fs.W_OK);
let fileBuffer = fs.readFileSync(filePath)
let suffix = filePath.match(/\.(.*?)$/)[1];
let contentType = '';
switch(suffix) {
case 'css':
contentType = 'text/css';
break;
case 'js':
contentType = 'application/x-javascript';
break;
default:
contentType = 'text/plain';
}
res.writeHead(200, 'ok', {
'Content-Type': contentType
});
res.end(fileBuffer);
} catch(e) {
console.log(e)
res.writeHead(404, 'bad request');
res.end();
}
}
});
server.listen(4001);