forked from jaywcjlove/sgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·187 lines (148 loc) · 5.12 KB
/
index.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
var http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs"),
net = require("net"),
color = require('colors-cli'),
iconv = require('iconv-lite'),
ctype = require("./lib/content-type"),
catalog = require('./lib/catalog'),
confproxy = require('./lib/get-proxy-config'),
query = require("querystring"), //解析POST请求
__port = 1987,
cors = false,
server;
require('colors-cli/toxic');
module.exports = server;
connListener = function(request, response) {
var uri = url.parse(request.url).pathname,
filename = path.join(process.cwd(), uri),
_header = !cors ? {
}:{
"Access-Control-Allow-Origin":"*",
'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,OPTIONS',
'Access-Control-Allow-Headers':'Content-Type, Authorization, Content-Length, X-Requested-With, Accept, x-csrf-token, origin'
};
var ext = path.parse(request.url.replace(/\?.*$/g, "")).ext.replace('.','');
var pxval = confproxy[request.method+' '+uri];
if(pxval){
var postData = null,arr = [];
request.addListener("data",function(postchunk){
arr.push(postchunk)
})
//POST结束输出结果
request.addListener("end",function(){
var data= Buffer.concat(arr).toString(),ret;
try{
ret = JSON.parse(data);
}catch(err){}
request.body = ret;
if(typeof pxval === "function"){
pxval = pxval(ret?ret:data,request.url);
}
response.writeHead(200, {
"Content-Type":(function(){
if(isJson(pxval) || Object.prototype.toString.call(pxval)){
return ctype.getContentType('json') + ';charset=utf-8';
}else if(typeof pxval == 'string'){
return ctype.getContentType('html') + ';charset=utf-8';
}
return '';
})()
});
response.writeHead(200,_header);
response.write( iconv.encode(JSON.stringify(pxval), 'utf-8').toString('binary') , "binary");
response.end();
commandLog(200,request,response)
})
return;
}
if(ext) _header['Content-Type'] = ctype.getContentType(ext);
// url 解码
filename = decodeURIComponent(filename);
var html = catalog(process.cwd()+request.url);
if( fs.existsSync(filename) && fs.statSync(filename).isDirectory() && fs.existsSync(filename + '/index.html') ) filename += '/index.html';
if( fs.existsSync(filename) && fs.statSync(filename).isFile() ){
fs.readFile(filename, "binary", function(err, file) {
response.writeHead(200,_header);
response.write(file, "binary");
response.end();
commandLog(200,request,response)
return;
});
}else{
response.writeHead(404, {});
response.write(html);
response.end();
commandLog(404,request,response)
return;
}
}
function isJson(obj){
return typeof(obj) == "object"
&& Object.prototype.toString.call(obj).toLowerCase() == "[object object]"
&& !obj.length;
}
// 命令行颜色显示
function commandLog(staus,request,response){
var code = response.statusCode;
if(code === 200){
console.log( ('INFO ' + request.method + ' ' + code.toString() ).green_bt + ' ' + request.url )
}else{
console.log( ('INFO ' + request.method + ' ' + code.toString()).red_bt + ' ' + request.url );
}
}
// 检测port是否存在
function probe(port, callback) {
var server = net.createServer().listen(port)
var calledOnce = false
var timeoutRef = setTimeout(function () {
calledOnce = true
callback(false,port)
}, 2000)
timeoutRef.unref()
var connected = false
server.on('listening', function() {
clearTimeout(timeoutRef)
if (server)
server.close()
if (!calledOnce) {
calledOnce = true
callback(true,port)
}
})
server.on('error', function(err) {
clearTimeout(timeoutRef)
var result = true
if (err.code === 'EADDRINUSE')
result = false
if (!calledOnce) {
calledOnce = true
callback(result,port)
}
})
}
// 启动服务
function serverStart(_port){
probe(_port,function(bl,_pt){
if(bl === true){
// ssr(_pt)
server = http.createServer(connListener);
server = server.listen(parseInt(_pt, 10));
console.log("\n Static file server running at" + color.green("\n\n=> http://localhost:" + _pt ) + '\n');
}else{
serverStart(_pt+1)
}
})
}
function server(argv){
var pt = '';
if(argv && argv.port) pt = argv.port;
else pt = __port;
if(argv && argv.port === true) pt = __port;
(argv && argv.cors) ? cors = true : cors = false;
if(argv && argv.proxy){
confproxy = confproxy(argv.proxy);
}
serverStart(pt);
}