简易nodeserver,含mock

还是自己写的东西合手。解决了一些以前碰到的问题。

Code

代码折叠 代码展开
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
const port = 3001;
const baseDir = './';
const defIndex = 'index.html';
const mockApiPrefix = '/api/';
const mockData = {
[mockApiPrefix+'a']: {
code:'200', msg: '成功1', data: {a: 'aaa', bg: '123ss'}
},
[mockApiPrefix+'b']:{
code:'200', msg: '成功2', data: {b: 'bbb', sf: '456ss'}
}
};


const http = require('http'), fs = require('fs'), url = require('url'), path = require('path'), os = require('os'),
mine = { 'css': 'text/css', 'gif': 'image/gif', 'html': 'text/html', 'ico': 'image/x-icon', 'xml': 'text/xml', 'jpeg': 'image/jpeg', 'jpg': 'image/jpeg', 'js': 'text/javascript', 'json': 'application/json', 'pdf': 'application/pdf', 'png': 'image/png', 'svg': 'image/svg+xml', 'swf': 'application/x-shockwave-flash', 'tiff': 'image/tiff', 'txt': 'text/plain', 'wav': 'audio/x-wav', 'wma': 'audio/x-ms-wma', 'wmv': 'video/x-ms-wmv'},
clientIP = (() => {
let nets = os.networkInterfaces();
for (let a in nets) {
let ifaces = nets[a];
for (let o in ifaces) {
if (ifaces[o].family == 'IPv4' && !ifaces[o].internal) return ifaces[o].address;
}
}
return '';
})();
http.createServer(function (req, res) {
const mockApi = url => {
console.log(`++++ [ajax]: ${url}`);
let apiUrl = mockApiPrefix.indexOf('/')===0 ? url : url.slice(1);
if(apiUrl in mockData){
res.writeHead(200, { 'Content-Type': 'application/json;charset=UTF-8' });
res.end(JSON.stringify(mockData[apiUrl]));
}else{
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('no data & no such url');
}
console.log(` ...done`);
};
const readHtml = name => {
console.log(`++++ request: ${name}`);
let status = 200, exist = fs.existsSync(name), data;
if(exist) data = fs.readFileSync(name, 'utf-8');
else data = `file:${name} not exist!`, status = 404;
res.writeHead(status, {'Content-Type': 'text/html'});
res.end(data);
console.log(` ...done`);
};
const readBinary = name =>{
console.log(`++++ request: ${name}`);
let exist = fs.existsSync(name);
if(exist){
res.writeHead(200, {'Content-Type': mine[ext] || 'text/plain'});
res.end(fs.readFileSync(name, 'binary'), 'binary');
}else{
res.writeHead(404, {'Content-Type': 'text/html'});
res.end(`file:${name} not exist!`);
}
console.log(` ...done`);
};
let pathname = url.parse(req.url).pathname, realPath = path.join(baseDir, pathname), ext = path.extname(realPath);
ext = ext ? ext.slice(1) : 'unknown';
if(pathname==='/') readHtml(path.join(baseDir, defIndex));
else if(ext === 'html') readHtml(realPath);
else if(ext in mine) readBinary(realPath);
else if(pathname.indexOf(mockApiPrefix)>-1) mockApi(pathname);
else{
console.log(`++++ request: / => ${realPath}`);
res.writeHead(404, {'Content-Type': 'text/html'});
res.write('no data');
console.log(` ...done`);
res.end();
}

}).listen(port, '0.0.0.0', function () {
console.log('===== Server running: localhost => http://%s:%s =============================================', clientIP || 'localhost', port);
});