ming_node 2.2.7 → 2.6.0

Sign up to get free protection for your applications and to get access to all the features.
package/index.js CHANGED
@@ -1,357 +1,367 @@
1
1
  /**
2
- * File : MemoryBaseRpcApi.js
2
+ * File : index.js
3
3
  * By : Minglie
4
4
  * QQ: 934031452
5
5
  * Date :2021.12.01
6
- * version :2.2.7
6
+ * version :2.6.0
7
7
  */
8
- var http = require('http');
9
- var https = require('https');
10
- var url_module = require('url');
11
- var querystring = require('querystring');
12
- var fs = require('fs');
13
- var path = require('path');
14
- var child_process = require('child_process');
15
- var EventEmitter = require('events').EventEmitter;
16
- var event = new EventEmitter();
17
- var privateObj = {};//本文件私有对象
18
- var M = {};
19
- M.privateObj=privateObj;
20
- M.sessions = {}//保存session
21
- M.con_display_status_enable = false;//是否显示响应状态码
22
- M.cookie = "JSESSIONID=" + "6E202D5A022EBD62705AA436EC54963B";//请求携带的cook
23
- M.reqComQueryparams = undefined;//请求的公共的查询参数
24
- M.reqComHeaders = undefined;//请求的公共请求头
25
- M.host = "http://127.0.0.1:7001";
26
- M.log_file_enable = true;//将日志输出到文件
27
- M.log_console_enable = true;//将日志输出到控制台
28
- M.log_path = "./M.log";//输出日志文件路径
29
- M.map_path = "./M_map.json";//全局作用域路径
30
- M.database_path = "./M_database.json";//文件型数据库路径
31
- M.log_display_time = true;//日志是否显示当前时间
32
- M.httpProxy = {};// http 代理配置
33
- M._sseClientMap=new Map();
34
- M._sseHeatTime=3000;
35
- M._moduleMap=new Map();//模块map
36
- M.httpBefore = (d) => {
37
- return d
38
- }
39
- M.httpEnd = (d) => {
40
- }
41
- //全局缓存map
42
- M._globle_cacheMap = {}
43
- //全局对象缓存
44
- M._globle_lib_cacheMap={}
45
- //全局插件地址缓存
46
- M._globle_plugin_url_cacheMap={};
47
- //全局插件
48
- M._globle_plugin=new Set();
49
- M._node_lib_path=process.env.NODE_PATH;
50
- //远程静态资源路径
51
- M.remoteStaticPath = "https://minglie.gitee.io/mingpage/static";
52
- M.remoteStaticPathEnable = true;
53
- //代理服务器配置
54
- M.proxyHost = "http://127.0.0.1:8888"
55
- M.proxyHost = "";
56
-
57
- M.setModule=function (key,module){
8
+ var http = require('http');
9
+ var https = require('https');
10
+ var url_module = require('url');
11
+ var querystring = require('querystring');
12
+ var fs = require('fs');
13
+ var path = require('path');
14
+ var child_process = require('child_process');
15
+ var EventEmitter = require('events').EventEmitter;
16
+ var event = new EventEmitter();
17
+ var privateObj = {};//本文件私有对象
18
+ var M = {};
19
+ M.privateObj=privateObj;
20
+ M.sessions = {}//保存session
21
+ M.con_display_status_enable = false;//是否显示响应状态码
22
+ M.cookie = "JSESSIONID=" + "6E202D5A022EBD62705AA436EC54963B";//请求携带的cook
23
+ M.reqComQueryparams = undefined;//请求的公共的查询参数
24
+ M.reqComHeaders = undefined;//请求的公共请求头
25
+ M.host = "http://127.0.0.1:7001";
26
+ M.log_file_enable = true;//将日志输出到文件
27
+ M.log_console_enable = true;//将日志输出到控制台
28
+ M.log_path = "./M.log";//输出日志文件路径
29
+ M.map_path = "./M_map.json";//全局作用域路径
30
+ M.database_path = "./M_database.json";//文件型数据库路径
31
+ M.log_display_time = true;//日志是否显示当前时间
32
+ M.httpProxy = {};// http 代理配置
33
+ M._sseClientMap=new Map();
34
+ M._sseHeatTime=3000;
35
+ M._moduleMap=new Map();//模块map
36
+ M.httpBefore = (d) => {
37
+ return d
38
+ }
39
+ M.httpEnd = (d) => {
40
+ }
41
+ //全局缓存map
42
+ M._globle_cacheMap = {}
43
+ //全局对象缓存
44
+ M._globle_lib_cacheMap={}
45
+ //全局插件地址缓存
46
+ M._globle_plugin_url_cacheMap={};
47
+ //全局插件
48
+ M._globle_plugin=new Set();
49
+ M._node_lib_path=process.cwd()+"/.ming_node_cacke";
50
+ //远程静态资源路径
51
+ M.remoteStaticPath = "https://minglie.gitee.io/mingpage/static";
52
+ M.remoteStaticPathEnable = true;
53
+ //代理服务器配置
54
+ M.proxyHost = "http://127.0.0.1:8888"
55
+ M.proxyHost = "";
56
+ M.IO={}
57
+ M.setModule=function (key,module){
58
58
  M._moduleMap.set(key,module);
59
- }
60
- M.getModule=function (key){
59
+ }
60
+ M.getModule=function (key){
61
61
  M._moduleMap.get(key);
62
- }
62
+ }
63
63
 
64
+ M.getGloblePlugin=(pluginKey)=>{
65
+ let plugin=null;
66
+ M._globle_plugin.forEach(u=>{
67
+ if(u.key==pluginKey){
68
+ plugin=u;
69
+ }
70
+ })
71
+ return plugin;
72
+ }
73
+
74
+
75
+ /**
76
+ * ----------------------客户端START--------------------------------------------
77
+ */
78
+ //解析对象或函数返回值
79
+ privateObj.getFunctionOrObjResult = function (objOrFunc, obj) {
80
+ let c1;
81
+ if (!objOrFunc) {
82
+ return obj;
83
+ }
84
+ if (typeof objOrFunc == "function") {
85
+ c1 = objOrFunc();
86
+ } else {
87
+ c1 = objOrFunc;
88
+ }
89
+ return Object.assign(obj, c1);
90
+ }
91
+
92
+ //将对象追加到url上
93
+ privateObj.appendDataToUrl = function (url, data) {
94
+ let getData = "";
95
+ if (data) {
96
+ getData = querystring.stringify(data);
97
+ //url携带参数了
98
+ if (url.indexOf("?") > 0) {
99
+ getData = "&" + getData;
100
+ } else {
101
+ getData = "?" + getData;
102
+ }
103
+ }
104
+ let r = url + getData;
105
+ return r;
106
+ }
64
107
 
65
- /**
66
- * ----------------------客户端START--------------------------------------------
67
- */
68
- //解析对象或函数返回值
69
- privateObj.getFunctionOrObjResult = function (objOrFunc, obj) {
70
- let c1;
71
- if (!objOrFunc) {
72
- return obj;
73
- }
74
- if (typeof objOrFunc == "function") {
75
- c1 = objOrFunc();
76
- } else {
77
- c1 = objOrFunc;
78
- }
79
- return Object.assign(obj, c1);
80
- }
81
-
82
- //将对象追加到url上
83
- privateObj.appendDataToUrl = function (url, data) {
84
- let getData = "";
85
- if (data) {
86
- getData = querystring.stringify(data);
87
- //url携带参数了
88
- if (url.indexOf("?") > 0) {
89
- getData = "&" + getData;
90
- } else {
91
- getData = "?" + getData;
92
- }
93
- }
94
- let r = url + getData;
95
- return r;
96
- }
97
-
98
108
  M.get = function (url, callback, data, headers) {
99
- if (typeof callback == "function") {
100
-
101
- } else {
102
- headers = data || {};
103
- data = callback;
104
- callback = () => {
105
- };
106
- }
107
- if (headers) {
108
- } else {
109
- headers = {
110
- 'Content-Type': 'application/json',
111
- 'Cookie': M.cookie
112
- }
113
- }
114
- let getData = "";
115
- if (data || M.reqComQueryparams) {
116
- data = privateObj.getFunctionOrObjResult(M.reqComQueryparams, data)
117
- getData = querystring.stringify(data);
118
- //url携带参数了
119
- if (url.indexOf("?") > 0) {
120
- getData = "&" + getData;
121
- } else {
122
- getData = "?" + getData;
123
- }
124
- }
125
- //合并请求头
126
- headers = privateObj.getFunctionOrObjResult(M.reqComHeaders, headers)
127
- var html = '';
128
- var urlObj = url_module.parse(url)
129
- var options = {
130
- hostname: urlObj.hostname,
131
- port: urlObj.port,
132
- path: urlObj.path + getData,
133
- method: 'GET',
134
- headers: headers
135
- }
136
- if (Object.keys(M.httpProxy).length > 0) {
137
- options.host = M.httpProxy.host;
138
- options.port = M.httpProxy.port;
139
- options.path = url + getData;
140
- delete options.hostname;
141
- }
142
- let reqHttp = http;
143
- if (url.startsWith("https")) {
144
- reqHttp = https;
145
- }
146
-
147
- return new Promise((resolve, reject) => {
148
- options = M.httpBefore(options);
149
- if (options == false) {
150
- return;
151
- }
152
- var req = reqHttp.request(options, function (res) {
153
- if (M.con_display_status_enable) console.log('STATUS:' + res.statusCode);
154
- if (global.debug && res.statusCode != 200) {
155
- while (1) {
156
- M.sleep(1000);
157
- console.log('STATUS:' + res.statusCode);
158
- console.log("--------ERROR:" + res.req.path + "-------------");
159
- }
160
- }
161
- res.setEncoding('utf-8');
162
- res.on('data', function (chunk) {
163
- html += chunk;
164
- });
165
- res.on('end', function () {
166
- callback(html, res);
167
- try {
168
- html = JSON.parse(html)
169
- } catch (e) {
170
- html = html;
171
- }
172
- M.httpEnd(html);
173
- resolve(html);
174
- });
175
- });
176
- req.on('error', function (err) {
177
- reject(err);
178
- console.error(err);
179
-
180
- });
181
- req.end();
182
- })
183
- }
109
+ if (typeof callback == "function") {
110
+
111
+ } else {
112
+ headers = data || {};
113
+ data = callback;
114
+ callback = () => {
115
+ };
116
+ }
117
+ if (headers) {
118
+ } else {
119
+ headers = {
120
+ 'Content-Type': 'application/json',
121
+ 'Cookie': M.cookie
122
+ }
123
+ }
124
+ let getData = "";
125
+ if (data || M.reqComQueryparams) {
126
+ data = privateObj.getFunctionOrObjResult(M.reqComQueryparams, data)
127
+ getData = querystring.stringify(data);
128
+ //url携带参数了
129
+ if (url.indexOf("?") > 0) {
130
+ getData = "&" + getData;
131
+ } else {
132
+ getData = "?" + getData;
133
+ }
134
+ }
135
+ //合并请求头
136
+ headers = privateObj.getFunctionOrObjResult(M.reqComHeaders, headers)
137
+ var html = '';
138
+ var urlObj = url_module.parse(url)
139
+ var options = {
140
+ hostname: urlObj.hostname,
141
+ port: urlObj.port,
142
+ path: urlObj.path + getData,
143
+ method: 'GET',
144
+ headers: headers
145
+ }
146
+ if (Object.keys(M.httpProxy).length > 0) {
147
+ options.host = M.httpProxy.host;
148
+ options.port = M.httpProxy.port;
149
+ options.path = url + getData;
150
+ delete options.hostname;
151
+ }
152
+ let reqHttp = http;
153
+ if (url.startsWith("https")) {
154
+ reqHttp = https;
155
+ }
156
+
157
+ return new Promise((resolve, reject) => {
158
+ options = M.httpBefore(options);
159
+ if (options == false) {
160
+ return;
161
+ }
162
+ var req = reqHttp.request(options, function (res) {
163
+ if (M.con_display_status_enable) console.log('STATUS:' + res.statusCode);
164
+ if (global.debug && res.statusCode != 200) {
165
+ while (1) {
166
+ M.sleep(1000);
167
+ console.log('STATUS:' + res.statusCode);
168
+ console.log("--------ERROR:" + res.req.path + "-------------");
169
+ }
170
+ }
171
+ res.setEncoding('utf-8');
172
+ res.on('data', function (chunk) {
173
+ html += chunk;
174
+ });
175
+ res.on('end', function () {
176
+ callback(html, res);
177
+ try {
178
+ html = JSON.parse(html)
179
+ } catch (e) {
180
+ html = html;
181
+ }
182
+ M.httpEnd(html);
183
+ resolve(html);
184
+ });
185
+ });
186
+ req.on('error', function (err) {
187
+ reject(err);
188
+ console.error(err);
189
+
190
+ });
191
+ req.end();
192
+ })
193
+ }
184
194
  M._request = function (url, callback, data, headers,methed) {
185
- if (typeof callback == "function") {
186
-
187
- } else {
188
- headers = data || {};
189
- data = callback;
190
- callback = () => {
191
- };
192
- }
193
-
194
- url = privateObj.appendDataToUrl(url, M.reqComQueryparams);
195
- var html = '';
196
- var urlObj = url_module.parse(url)
197
- //发送 http Post 请求
198
- var postData = querystring.stringify(data);
199
- if( headers["Content-Type"]==undefined){
200
- headers["Content-Type"] ="application/json";
201
- }
202
- if (headers["Content-Type"] == "application/json") {
203
- postData = JSON.stringify(data);
204
- }else {
205
- headers = {
206
- 'Content-Type': 'application/x-www-form-urlencoded; ' +
207
- 'charset=UTF-8',
208
- 'Content-Length': Buffer.byteLength(postData)
209
- }
210
- }
211
-
212
- //合并请求头
213
- headers = privateObj.getFunctionOrObjResult(M.reqComHeaders, headers)
214
- var options = {
215
- hostname: urlObj.hostname,
216
- port: urlObj.port,
217
- path: urlObj.path,
218
- method: methed,
219
- headers: headers
220
- }
221
- if (Object.keys(M.httpProxy).length > 0) {
222
- options.host = M.httpProxy.host;
223
- options.port = M.httpProxy.port;
224
- options.path = url;
225
- delete options.hostname;
226
- }
227
- let reqHttp = http;
228
- if (url.startsWith("https")) {
229
- reqHttp = https;
230
- }
231
-
232
- return new Promise((resolve, reject) => {
233
- var req = reqHttp.request(options, function (res) {
234
- options = M.httpBefore(options);
235
- if (options == false) {
236
- return;
237
- }
238
- if (M.con_display_status_enable) console.log('STATUS:' + res.statusCode);
239
- if (global.debug && res.statusCode != 200) {
240
- while (1) {
241
- M.sleep(1000);
242
- console.log('STATUS:' + res.statusCode);
243
- console.log("--------ERROR:" + res.req.path + "-------------");
244
- }
245
- }
246
- // console.log('headers:',JSON.stringify(res.headers));
247
- res.setEncoding('utf-8');
248
- res.on('data', function (chunk) {
249
- html += chunk;
250
- });
251
- res.on('end', function () {
252
- callback(html, res);
253
- try {
254
- html = JSON.parse(html)
255
- } catch (e) {
256
- html = html;
257
- }
258
- M.httpEnd(html);
259
- resolve(html);
260
- });
261
-
262
- });
263
-
264
- req.on('error', function (err) {
265
- console.error(err);
266
- });
267
- if(methed !="GET") req.write(postData);
268
- req.end();
269
- })
270
- }
195
+ if (typeof callback == "function") {
196
+
197
+ } else {
198
+ headers = data || {};
199
+ data = callback;
200
+ callback = () => {
201
+ };
202
+ }
203
+
204
+ url = privateObj.appendDataToUrl(url, M.reqComQueryparams);
205
+ var html = '';
206
+ var urlObj = url_module.parse(url)
207
+ //发送 http Post 请求
208
+ var postData = querystring.stringify(data);
209
+ if( headers["Content-Type"]==undefined){
210
+ headers["Content-Type"] ="application/json";
211
+ }
212
+ if (headers["Content-Type"] == "application/json") {
213
+ postData = JSON.stringify(data);
214
+ }else {
215
+ headers = {
216
+ 'Content-Type': 'application/x-www-form-urlencoded; ' +
217
+ 'charset=UTF-8',
218
+ 'Content-Length': Buffer.byteLength(postData)
219
+ }
220
+ }
221
+
222
+ //合并请求头
223
+ headers = privateObj.getFunctionOrObjResult(M.reqComHeaders, headers)
224
+ var options = {
225
+ hostname: urlObj.hostname,
226
+ port: urlObj.port,
227
+ path: urlObj.path,
228
+ method: methed,
229
+ headers: headers
230
+ }
231
+ if (Object.keys(M.httpProxy).length > 0) {
232
+ options.host = M.httpProxy.host;
233
+ options.port = M.httpProxy.port;
234
+ options.path = url;
235
+ delete options.hostname;
236
+ }
237
+ let reqHttp = http;
238
+ if (url.startsWith("https")) {
239
+ reqHttp = https;
240
+ }
241
+
242
+ return new Promise((resolve, reject) => {
243
+ var req = reqHttp.request(options, function (res) {
244
+ options = M.httpBefore(options);
245
+ if (options == false) {
246
+ return;
247
+ }
248
+ if (M.con_display_status_enable) console.log('STATUS:' + res.statusCode);
249
+ if (global.debug && res.statusCode != 200) {
250
+ while (1) {
251
+ M.sleep(1000);
252
+ console.log('STATUS:' + res.statusCode);
253
+ console.log("--------ERROR:" + res.req.path + "-------------");
254
+ }
255
+ }
256
+ // console.log('headers:',JSON.stringify(res.headers));
257
+ res.setEncoding('utf-8');
258
+ res.on('data', function (chunk) {
259
+ html += chunk;
260
+ });
261
+ res.on('end', function () {
262
+ callback(html, res);
263
+ try {
264
+ html = JSON.parse(html)
265
+ } catch (e) {
266
+ html = html;
267
+ }
268
+ M.httpEnd(html);
269
+ resolve(html);
270
+ });
271
+
272
+ });
273
+
274
+ req.on('error', function (err) {
275
+ console.error(err);
276
+ });
277
+ if(methed !="GET") req.write(postData);
278
+ req.end();
279
+ })
280
+ }
271
281
  M.post=(url, callback, data, headers)=>M._request(url, callback, data, headers,"POST")
272
282
  M.delete=(url, callback, data, headers)=>M._request(url, callback, data, headers,"DELETE")
273
283
  M.put=(url, callback, data, headers)=>M._request(url, callback, data, headers,"PUT")
274
284
  M.postJson = function (url, callback, data, headers) {
275
- if (typeof callback == "function") {
276
-
277
- } else {
278
- headers = data || {};
279
- data = callback;
280
- callback = () => {
281
- };
282
- }
283
- url = privateObj.appendDataToUrl(url, M.reqComQueryparams);
284
- var html = '';
285
- var urlObj = url_module.parse(url)
286
- //发送 http Post 请求
287
- var postData = JSON.stringify(data);
288
- if (!headers) {
289
- headers = {
290
- 'Content-Type': 'application/json; ' +
291
- 'charset=UTF-8',
292
- 'Cookie': M.cookie
293
- }
294
- }
295
- //合并请求头
296
- headers = privateObj.getFunctionOrObjResult(M.reqComHeaders, headers)
297
- var options = {
298
- hostname: urlObj.hostname,
299
- port: urlObj.port,
300
- path: urlObj.path,
301
- method: 'POST',
302
- headers: headers
303
- }
304
- if (Object.keys(M.httpProxy).length > 0) {
305
- options.host = M.httpProxy.host;
306
- options.port = M.httpProxy.port;
307
- options.path = url;
308
- delete options.hostname;
309
- }
310
- let reqHttp = http;
311
- if (url.startsWith("https")) {
312
- reqHttp = https;
313
- }
314
-
315
- return new Promise((resolve, reject) => {
316
-
317
- var req = reqHttp.request(options, function (res) {
318
- options = M.httpBefore(options);
319
- if (options == false) {
320
- return;
321
- }
322
- if (M.con_display_status_enable) console.log('STATUS:' + res.statusCode);
323
- if (global.debug && res.statusCode != 200) {
324
- while (1) {
325
- M.sleep(1000);
326
- console.log('STATUS:' + res.statusCode);
327
- console.log("--------ERROR:" + res.req.path + "-------------");
328
- }
329
- }
330
- // console.log('headers:',JSON.stringify(res.headers));
331
- res.setEncoding('utf-8');
332
- res.on('data', function (chunk) {
333
- html += chunk;
334
- });
335
- res.on('end', function () {
336
- callback(html, res);
337
- try {
338
- html = JSON.parse(html)
339
- } catch (e) {
340
- html = html;
341
- }
342
- M.httpEnd(html);
343
- resolve(html);
344
- });
345
-
346
- });
347
-
348
- req.on('error', function (err) {
349
- console.error(err);
350
- });
351
- req.write(postData);
352
- req.end();
353
- })
354
- }
285
+ if (typeof callback == "function") {
286
+
287
+ } else {
288
+ headers = data || {};
289
+ data = callback;
290
+ callback = () => {
291
+ };
292
+ }
293
+ url = privateObj.appendDataToUrl(url, M.reqComQueryparams);
294
+ var html = '';
295
+ var urlObj = url_module.parse(url)
296
+ //发送 http Post 请求
297
+ var postData = JSON.stringify(data);
298
+ if (!headers) {
299
+ headers = {
300
+ 'Content-Type': 'application/json; ' +
301
+ 'charset=UTF-8',
302
+ 'Cookie': M.cookie
303
+ }
304
+ }
305
+ //合并请求头
306
+ headers = privateObj.getFunctionOrObjResult(M.reqComHeaders, headers)
307
+ var options = {
308
+ hostname: urlObj.hostname,
309
+ port: urlObj.port,
310
+ path: urlObj.path,
311
+ method: 'POST',
312
+ headers: headers
313
+ }
314
+ if (Object.keys(M.httpProxy).length > 0) {
315
+ options.host = M.httpProxy.host;
316
+ options.port = M.httpProxy.port;
317
+ options.path = url;
318
+ delete options.hostname;
319
+ }
320
+ let reqHttp = http;
321
+ if (url.startsWith("https")) {
322
+ reqHttp = https;
323
+ }
324
+
325
+ return new Promise((resolve, reject) => {
326
+
327
+ var req = reqHttp.request(options, function (res) {
328
+ options = M.httpBefore(options);
329
+ if (options == false) {
330
+ return;
331
+ }
332
+ if (M.con_display_status_enable) console.log('STATUS:' + res.statusCode);
333
+ if (global.debug && res.statusCode != 200) {
334
+ while (1) {
335
+ M.sleep(1000);
336
+ console.log('STATUS:' + res.statusCode);
337
+ console.log("--------ERROR:" + res.req.path + "-------------");
338
+ }
339
+ }
340
+ // console.log('headers:',JSON.stringify(res.headers));
341
+ res.setEncoding('utf-8');
342
+ res.on('data', function (chunk) {
343
+ html += chunk;
344
+ });
345
+ res.on('end', function () {
346
+ callback(html, res);
347
+ try {
348
+ html = JSON.parse(html)
349
+ } catch (e) {
350
+ html = html;
351
+ }
352
+ M.httpEnd(html);
353
+ resolve(html);
354
+ });
355
+
356
+ });
357
+
358
+ req.on('error', function (err) {
359
+ console.error(err);
360
+ });
361
+ req.write(postData);
362
+ req.end();
363
+ })
364
+ }
355
365
  //数据请求规范
356
366
  M.request={}
357
367
  M.request.get=M.get;
@@ -360,516 +370,521 @@ M.request.delete=M.delete;
360
370
  M.request.put=M.put;
361
371
 
362
372
 
363
- M.require =async function (url,noCache) {
364
- //如果需要缓存
365
- let fileName=M.getFileNameByUrl(url);
366
- if(!noCache){
367
- if(fs.existsSync(M._node_lib_path+"/"+fileName)){
368
- return require(M._node_lib_path+"/"+fileName)
369
- }
370
- }
371
- let ht = "http";
372
- if (url.startsWith("https")) {
373
- ht = "https";
374
- }
375
- console.log("req require remote url:", url);
376
- let promise = new Promise(function (reslove, reject) {
377
- require(ht).get(url, function (req, res) {
378
- var d = '';
379
- req.on('data', (data) => {
380
- d += data;
381
- });
382
- req.on('end', () => {
383
- let r = "";
384
- try {
385
- if(fileName.endsWith(".js")){
386
- //如果需要缓存
387
- if(!noCache){
388
- M.writeFile(M._node_lib_path+"/"+fileName,d);
389
- }
390
- r= eval(d);
391
- }else {
392
- r = JSON.parse(d)
393
- }
394
- } catch (e) {
395
- r = d;
396
- }
397
- reslove(r);
398
- });
399
- req.on('error', (e) => reject(e.message));
400
- })
401
- });
402
- return promise;
403
- }
404
-
405
- M.import=async function (url,callback){
406
- if(M._globle_lib_cacheMap[url]){
407
- return M._globle_lib_cacheMap[url];
408
- }
409
- if(!callback){
410
- let r=await M.get(url)
411
- r= eval(r)
412
- M._globle_lib_cacheMap[url]=r;
413
- return r
414
- }else {
415
- let r= callback()
416
- M._globle_lib_cacheMap[url]=r;
417
- return r
418
- }
419
-
420
- }
421
-
422
- /**
423
- *下载图片
424
- */
425
- M.download = function (url, file, callback) {
426
- var func = http;
427
- if (url.indexOf("https") >= 0) {
428
- func = https;
429
- }
430
- func.get(url, function (res) {
431
- res.setEncoding('binary');//转成二进制
432
- var content = '';
433
- res.on('data', function (data) {
434
- content += data;
435
- }).on('end', function () {
436
- if (callback) callback();
437
- fs.writeFile(file, content, 'binary', function (err) {
438
- if (err) throw err;
439
- });
440
- });
441
- });
442
- }
443
- /**
444
- *下载所有图片
445
- */
446
- M.downloadAllImg = function (url, file, callback) {
447
- var urlObj = url_module.parse(url)
448
- var options = {
449
- hostname: urlObj.hostname,
450
- }
451
- var func = http;
452
- if (url.indexOf("https") >= 0) {
453
- func = https;
454
- }
455
- var req = func.request(options, function (res) {
456
- res.on('data', function (data) {
457
- //Buffer
458
- var string = data.toString();
459
- var rule = /https?:\/\/.[^"]+\.(png|jpg|gif|jpeg)/gi;
460
- var ary = string.match(rule); //拿到所有jpg结尾的链接集合
461
- if (callback) callback(ary);
462
- var x = 0;
463
- for (var i in ary) {
464
- M.download(ary[i], file + (x++) + ary[i].substr(ary[i].lastIndexOf(".")));
465
- }
466
- });
467
- });
468
- req.end();
469
- }
470
-
471
- /**
472
- *打印结果前钩子
473
- */
474
- M.beforeLogData = function (res, desc) {
475
- console.log("-----" + desc + "-----" + res.req.path + "-------------");
476
- }
477
-
478
-
479
- /**
480
- *打印结果后钩子
481
- */
482
- M.afterLogData = function () {
483
-
484
- console.log("--END")
485
- }
486
-
487
- /**
488
- *简化get请求
489
- */
490
- M.get0 = function (url, data) {
491
- if (Array.isArray(url)) {
492
- for (let i = 0; i < url.length; i++) {
493
- M.get(
494
- M.host + url[i],
495
- function (data, res) {
496
- console.log("---------" + res.req.path + "------------");
497
- console.log(data);
498
- }, data
499
- );
500
- }
501
- } else {
502
- M.get(
503
- M.host + url,
504
- function (data) {
505
- console.log(data);
506
- }, data
507
- );
508
- }
509
-
510
- }
511
-
512
- /**
513
- *简化post请求
514
- */
515
- M.post0 = function (url, data) {
516
- M.post(
517
- M.host + url,
518
- function (data) {
519
- console.log(data);
520
- }, data
521
- );
522
- }
523
-
524
- M.postJson0 = function (url, data) {
525
- M.postJson(
526
- M.host + url,
527
- function (data) {
528
- console.log(data);
529
- }, data
530
- );
531
- }
532
-
533
- M.template = function (str) {
534
- return eval("`" + str + "`");
535
- }
536
-
537
-
538
- /**
539
- * ----------------------客户端END--------------------------------------------
540
- */
541
-
542
-
543
- /**
544
- * ----------------------数据持久化读写START--------------------------------------------
545
- */
546
-
547
- /**
548
- *递归创建文件夹
549
- */
550
- M.mkdir = function (dirpath, dirname) {
551
- //判断是否是第一次调用
552
- if (typeof dirname === "undefined") {
553
-
554
- if (dirpath.indexOf(".") > 0) {
555
- dirpath = path.dirname(dirpath);
556
- }
557
- if (fs.existsSync(dirpath)) {
558
- return;
559
- } else {
560
- M.mkdir(dirpath, path.dirname(dirpath));
561
- }
562
- } else {
563
- //判断第二个参数是否正常,避免调用时传入错误参数
564
- if (dirname !== path.dirname(dirpath)) {
565
- M.mkdir(dirpath);
566
- return;
567
- }
568
- if (fs.existsSync(dirname)) {
569
- fs.mkdirSync(dirpath)
570
- } else {
571
- M.mkdir(dirname, path.dirname(dirname));
572
- fs.mkdirSync(dirpath);
573
- }
574
- }
575
- }
576
- /**
577
- *文件夹拷贝
578
- */
579
- M.copyDir = function (src, dst) {
580
- let paths = fs.readdirSync(src); //同步读取当前目录
581
- paths.forEach(function (path) {
582
- var _src = src + '/' + path;
583
- var _dst = dst + '/' + path;
584
- fs.stat(_src, function (err, stats) { //stats 该对象 包含文件属性
585
- if (err) throw err;
586
- if (stats.isFile()) { //如果是个文件则拷贝
587
- let readable = fs.createReadStream(_src);//创建读取流
588
- let writable = fs.createWriteStream(_dst);//创建写入流
589
- readable.pipe(writable);
590
- } else if (stats.isDirectory()) { //是目录则 递归
591
- privateObj.checkDirectory(_src, _dst, M.copyDir);
592
- }
593
- });
594
- });
595
- }
596
-
597
- privateObj.checkDirectory = function (src, dst, callback) {
598
- fs.access(dst, fs.constants.F_OK, (err) => {
599
- if (err) {
600
- fs.mkdirSync(dst);
601
- callback(src, dst);
602
- } else {
603
- callback(src, dst);
604
- }
605
- });
606
- };
607
-
608
- M.readFile = function (file) {
609
- if (fs.existsSync(file)) {
610
- return fs.readFileSync(file, "utf-8");
611
- } else {
612
- return;
613
- }
614
- }
615
- M.writeFile = function (file, str) {
616
- fs.writeFileSync(file, str);
617
- }
618
- M.appendFile = function (file, str) {
619
- fs.appendFileSync(file, str);
620
- }
621
- /**
622
- 文件型数据库第一层封装
623
- */
624
- M.getObjByFile = function (file) {
625
- data = M.readFile(file) || "[]"
626
- var obj = JSON.parse(data.toString());
627
- return obj;
628
- }
629
- M.writeObjToFile = function (file, obj) {
630
- M.writeFile(file, JSON.stringify(obj));
631
- }
632
-
633
- M.addObjToFile = function (file, obj) {
634
- try {
635
- var d = M.getObjByFile(file);
636
- M.writeObjToFile(file, [...d, obj]);
637
- } catch (e) {
638
- M.writeObjToFile(file, [obj]);
639
- }
640
- }
641
- M.deleteObjByIdFile = function (file, id) {
642
- let ids = [];
643
- if (!Array.isArray(id)) {
644
- ids.push(id)
645
- } else {
646
- ids = id;
647
- }
648
- var d = M.getObjByFile(file);
649
- var d1 = M.getObjByFile(file);
650
- let d_num = 0;
651
- for (let i = 0; i < d1.length; i++) {
652
- if (ids.indexOf(d1[i].id) >= 0) {
653
- d.splice(i - d_num, 1);
654
- d_num++;
655
- if (ids.length == 1) break;
656
- }
657
- }
658
- M.writeObjToFile(file, d);
659
- }
660
-
661
- M.deleteObjByPropFile = function (file, o) {
662
- let o_key = Object.keys(o)[0];
663
- let o_val = o[o_key]
664
- var d = M.getObjByFile(file);
665
- var d1 = M.getObjByFile(file);
666
- let d_num = 0;
667
- for (let i = 0; i < d1.length; i++) {
668
- if (d1[i][o_key] == o_val) {
669
- d.splice(i - d_num, 1);
670
- d_num++;
671
- }
672
- }
673
- M.writeObjToFile(file, d);
674
- return d_num;
675
- }
676
-
677
- M.updateObjByIdFile = function (file, obj) {
678
- var d = M.getObjByFile(file);
679
- for (let i = 0; i < d.length; i++) {
680
- if (d[i].id == obj.id) {
681
- d.splice(i, 1, Object.assign(d[i],obj));
682
- break;
683
- }
684
- }
685
- M.writeObjToFile(file, d);
686
- }
687
- M.getObjByIdFile = function (file, id) {
688
- var d = M.getObjByFile(file);
689
- for (let i = 0; i < d.length; i++) {
690
- if (d[i].id == id) {
691
- return d[i];
692
- }
693
- }
694
- }
695
- M.listAllObjByPropFile = function (file, caseObj) {
696
- var d = M.getObjByFile(file);
697
- let o_keys = Object.keys(caseObj);
698
- if (caseObj && o_keys.length>0) {
699
- let r_list = [];
700
- let o_vals = Object.values(caseObj);
701
- for (let i = 0; i < d.length; i++) {
702
- let s=0;
703
- for (let j=0;j<o_keys.length;j++){
704
- if (d[i][o_keys[j]] != o_vals[j]) {
705
- break
706
- }
707
- s++;
708
- }
709
- if(s==o_keys.length){
710
- r_list.push(d[i]);
711
- }
712
- }
713
- return r_list;
714
- } else {
715
- return d;
716
- }
717
- }
718
- /**
719
- * 文件型数据库第二层封装
720
- */
721
- M.add = function (obj) {
722
- obj.id = M.randomStr();
723
- M.addObjToFile(M.database_path, obj);
724
- return obj;
725
- }
726
- M.update = function (obj) {
727
- M.updateObjByIdFile(M.database_path, obj);
728
- }
729
- M.deleteById = function (id) {
730
- M.deleteObjByIdFile(M.database_path, id);
731
- }
732
- M.deleteAll = function (o) {
733
- if (o) {
734
- M.deleteObjByPropFile(M.database_path, o);
735
- } else {
736
- M.writeObjToFile(M.database_path, []);
737
- }
738
- }
739
- M.deleteByProp = function (o) {
740
- M.deleteObjByPropFile(M.database_path, o);
741
- }
742
- M.getById = function (id) {
743
- return M.getObjByIdFile(M.database_path, id);
744
- }
745
- M.listAll = function (o) {
746
- if (o) {
747
- return M.listAllObjByPropFile(M.database_path, o);
748
- } else {
749
- return M.getObjByFile(M.database_path);
750
- }
751
- }
752
- M.listByProp = function (o) {
753
- return M.listAllObjByPropFile(M.database_path, o);
754
- }
755
- M.listByPage = function (startPage, limit, caseObj) {
756
- if (startPage <= 0) startPage = 1;
757
- let rows;
758
- if (caseObj) {
759
- rows = M.listByProp(caseObj);
760
- } else {
761
- rows = M.listAll();
762
- }
763
- let total = rows.length;
764
- rows = rows.splice((startPage - 1) * limit, limit)
765
- return {rows, total}
766
- }
767
- /**
768
- * 全局作用域
769
- * @param k
770
- * @param v
771
- */
772
- M.setAttribute = function (k, v) {
773
- let a = {}
774
- a[k] = v;
775
- a = JSON.stringify(a)
776
- a = JSON.parse(a);
777
- let preObj;
778
- try {
779
- preObj = M.getObjByFile(M.map_path);
780
- if (Array.isArray(preObj)) preObj = {};
781
- } catch (e) {
782
- preObj = {};
783
- }
784
-
785
- M.writeObjToFile(M.map_path, Object.assign(preObj, a));
786
- }
787
-
788
- M.getAttribute = function (k) {
789
- return M.getObjByFile(M.map_path)[k];
790
- }
791
- /**
792
- *逐行读取文件
793
- */
794
- M.readLine =async function (file, callback) {
795
- let lineCount=0;
796
- return new Promise((resolve, reject) =>{
797
- var remaining = '';
798
- var input = fs.createReadStream(file);
799
- input.on('data', function (data) {
800
- remaining += data;
801
- var index = remaining.indexOf('\n');
802
- while (index > -1) {
803
- var line = remaining.substring(0, index);
804
- remaining = remaining.substring(index + 1);
805
- lineCount++;
806
- callback(line);
807
- index = remaining.indexOf('\n');
808
- }
809
- });
810
- input.on('end', function () {
811
- if (remaining.length > 0) {
812
- resolve(lineCount);
813
- callback(remaining);
814
- }
815
- });
816
- } )
817
- }
818
-
819
-
820
- M.readCsvLine =async function (file, callback) {
373
+ M.require =async function (url,noCache) {
374
+ //如果需要缓存
375
+ let fileName=M.getFileNameByUrl(url);
376
+ let cacheFilePath= path.join(M._node_lib_path,fileName);
377
+ if(!noCache){
378
+
379
+ if(fs.existsSync(cacheFilePath)){
380
+ return require(cacheFilePath)
381
+ }
382
+ }
383
+ let ht = "http";
384
+ if (url.startsWith("https")) {
385
+ ht = "https";
386
+ }
387
+ console.log("req require remote url:", url);
388
+ let promise = new Promise(function (reslove, reject) {
389
+ require(ht).get(url, function (req, res) {
390
+ var d = '';
391
+ req.on('data', (data) => {
392
+ d += data;
393
+ });
394
+ req.on('end', () => {
395
+ let r = "";
396
+ try {
397
+ if(fileName.endsWith(".js")){
398
+ //如果需要缓存
399
+ if(!noCache){
400
+ if (!fs.existsSync(M._node_lib_path)) {
401
+ fs.mkdirSync(M._node_lib_path);
402
+ }
403
+ M.writeFile(cacheFilePath,d);
404
+ }
405
+ r= eval(d);
406
+ }else {
407
+ r = JSON.parse(d)
408
+ }
409
+ } catch (e) {
410
+ r = d;
411
+ }
412
+ reslove(r);
413
+ });
414
+ req.on('error', (e) => reject(e.message));
415
+ })
416
+ });
417
+ return promise;
418
+ }
419
+
420
+ M.import=async function (url,callback){
421
+ if(M._globle_lib_cacheMap[url]){
422
+ return M._globle_lib_cacheMap[url];
423
+ }
424
+ if(!callback){
425
+ let r=await M.get(url)
426
+ r= eval(r)
427
+ M._globle_lib_cacheMap[url]=r;
428
+ return r
429
+ }else {
430
+ let r= callback()
431
+ M._globle_lib_cacheMap[url]=r;
432
+ return r
433
+ }
434
+
435
+ }
436
+
437
+ /**
438
+ *下载图片
439
+ */
440
+ M.download = function (url, file, callback) {
441
+ var func = http;
442
+ if (url.indexOf("https") >= 0) {
443
+ func = https;
444
+ }
445
+ func.get(url, function (res) {
446
+ res.setEncoding('binary');//转成二进制
447
+ var content = '';
448
+ res.on('data', function (data) {
449
+ content += data;
450
+ }).on('end', function () {
451
+ if (callback) callback();
452
+ fs.writeFile(file, content, 'binary', function (err) {
453
+ if (err) throw err;
454
+ });
455
+ });
456
+ });
457
+ }
458
+ /**
459
+ *下载所有图片
460
+ */
461
+ M.downloadAllImg = function (url, file, callback) {
462
+ var urlObj = url_module.parse(url)
463
+ var options = {
464
+ hostname: urlObj.hostname,
465
+ }
466
+ var func = http;
467
+ if (url.indexOf("https") >= 0) {
468
+ func = https;
469
+ }
470
+ var req = func.request(options, function (res) {
471
+ res.on('data', function (data) {
472
+ //Buffer
473
+ var string = data.toString();
474
+ var rule = /https?:\/\/.[^"]+\.(png|jpg|gif|jpeg)/gi;
475
+ var ary = string.match(rule); //拿到所有jpg结尾的链接集合
476
+ if (callback) callback(ary);
477
+ var x = 0;
478
+ for (var i in ary) {
479
+ M.download(ary[i], file + (x++) + ary[i].substr(ary[i].lastIndexOf(".")));
480
+ }
481
+ });
482
+ });
483
+ req.end();
484
+ }
485
+
486
+ /**
487
+ *打印结果前钩子
488
+ */
489
+ M.beforeLogData = function (res, desc) {
490
+ console.log("-----" + desc + "-----" + res.req.path + "-------------");
491
+ }
492
+
493
+
494
+ /**
495
+ *打印结果后钩子
496
+ */
497
+ M.afterLogData = function () {
498
+
499
+ console.log("--END")
500
+ }
501
+
502
+ /**
503
+ *简化get请求
504
+ */
505
+ M.get0 = function (url, data) {
506
+ if (Array.isArray(url)) {
507
+ for (let i = 0; i < url.length; i++) {
508
+ M.get(
509
+ M.host + url[i],
510
+ function (data, res) {
511
+ console.log("---------" + res.req.path + "------------");
512
+ console.log(data);
513
+ }, data
514
+ );
515
+ }
516
+ } else {
517
+ M.get(
518
+ M.host + url,
519
+ function (data) {
520
+ console.log(data);
521
+ }, data
522
+ );
523
+ }
524
+
525
+ }
526
+
527
+ /**
528
+ *简化post请求
529
+ */
530
+ M.post0 = function (url, data) {
531
+ M.post(
532
+ M.host + url,
533
+ function (data) {
534
+ console.log(data);
535
+ }, data
536
+ );
537
+ }
538
+
539
+ M.postJson0 = function (url, data) {
540
+ M.postJson(
541
+ M.host + url,
542
+ function (data) {
543
+ console.log(data);
544
+ }, data
545
+ );
546
+ }
547
+
548
+ M.template = function (str) {
549
+ return eval("`" + str + "`");
550
+ }
551
+
552
+
553
+ /**
554
+ * ----------------------客户端END--------------------------------------------
555
+ */
556
+
557
+
558
+ /**
559
+ * ----------------------数据持久化读写START--------------------------------------------
560
+ */
561
+
562
+ /**
563
+ *递归创建文件夹
564
+ */
565
+ M.mkdir = function (dirpath, dirname) {
566
+ //判断是否是第一次调用
567
+ if (typeof dirname === "undefined") {
568
+
569
+ if (dirpath.indexOf(".") > 0) {
570
+ dirpath = path.dirname(dirpath);
571
+ }
572
+ if (fs.existsSync(dirpath)) {
573
+ return;
574
+ } else {
575
+ M.mkdir(dirpath, path.dirname(dirpath));
576
+ }
577
+ } else {
578
+ //判断第二个参数是否正常,避免调用时传入错误参数
579
+ if (dirname !== path.dirname(dirpath)) {
580
+ M.mkdir(dirpath);
581
+ return;
582
+ }
583
+ if (fs.existsSync(dirname)) {
584
+ fs.mkdirSync(dirpath)
585
+ } else {
586
+ M.mkdir(dirname, path.dirname(dirname));
587
+ fs.mkdirSync(dirpath);
588
+ }
589
+ }
590
+ }
591
+ /**
592
+ *文件夹拷贝
593
+ */
594
+ M.copyDir = function (src, dst) {
595
+ let paths = fs.readdirSync(src); //同步读取当前目录
596
+ paths.forEach(function (path) {
597
+ var _src = src + '/' + path;
598
+ var _dst = dst + '/' + path;
599
+ fs.stat(_src, function (err, stats) { //stats 该对象 包含文件属性
600
+ if (err) throw err;
601
+ if (stats.isFile()) { //如果是个文件则拷贝
602
+ let readable = fs.createReadStream(_src);//创建读取流
603
+ let writable = fs.createWriteStream(_dst);//创建写入流
604
+ readable.pipe(writable);
605
+ } else if (stats.isDirectory()) { //是目录则 递归
606
+ privateObj.checkDirectory(_src, _dst, M.copyDir);
607
+ }
608
+ });
609
+ });
610
+ }
611
+
612
+ privateObj.checkDirectory = function (src, dst, callback) {
613
+ fs.access(dst, fs.constants.F_OK, (err) => {
614
+ if (err) {
615
+ fs.mkdirSync(dst);
616
+ callback(src, dst);
617
+ } else {
618
+ callback(src, dst);
619
+ }
620
+ });
621
+ };
622
+
623
+ M.readFile = function (file) {
624
+ if (fs.existsSync(file)) {
625
+ return fs.readFileSync(file, "utf-8");
626
+ } else {
627
+ return;
628
+ }
629
+ }
630
+ M.writeFile = function (file, str) {
631
+ fs.writeFileSync(file, str);
632
+ }
633
+ M.appendFile = function (file, str) {
634
+ fs.appendFileSync(file, str);
635
+ }
636
+ /**
637
+ 文件型数据库第一层封装
638
+ */
639
+ M.getObjByFile = function (file) {
640
+ data = M.readFile(file) || "[]"
641
+ var obj = JSON.parse(data.toString());
642
+ return obj;
643
+ }
644
+ M.writeObjToFile = function (file, obj) {
645
+ M.writeFile(file, JSON.stringify(obj));
646
+ }
647
+
648
+ M.addObjToFile = function (file, obj) {
649
+ try {
650
+ var d = M.getObjByFile(file);
651
+ M.writeObjToFile(file, [...d, obj]);
652
+ } catch (e) {
653
+ M.writeObjToFile(file, [obj]);
654
+ }
655
+ }
656
+ M.deleteObjByIdFile = function (file, id) {
657
+ let ids = [];
658
+ if (!Array.isArray(id)) {
659
+ ids.push(id)
660
+ } else {
661
+ ids = id;
662
+ }
663
+ var d = M.getObjByFile(file);
664
+ var d1 = M.getObjByFile(file);
665
+ let d_num = 0;
666
+ for (let i = 0; i < d1.length; i++) {
667
+ if (ids.indexOf(d1[i].id) >= 0) {
668
+ d.splice(i - d_num, 1);
669
+ d_num++;
670
+ if (ids.length == 1) break;
671
+ }
672
+ }
673
+ M.writeObjToFile(file, d);
674
+ }
675
+
676
+ M.deleteObjByPropFile = function (file, o) {
677
+ let o_key = Object.keys(o)[0];
678
+ let o_val = o[o_key]
679
+ var d = M.getObjByFile(file);
680
+ var d1 = M.getObjByFile(file);
681
+ let d_num = 0;
682
+ for (let i = 0; i < d1.length; i++) {
683
+ if (d1[i][o_key] == o_val) {
684
+ d.splice(i - d_num, 1);
685
+ d_num++;
686
+ }
687
+ }
688
+ M.writeObjToFile(file, d);
689
+ return d_num;
690
+ }
691
+
692
+ M.updateObjByIdFile = function (file, obj) {
693
+ var d = M.getObjByFile(file);
694
+ for (let i = 0; i < d.length; i++) {
695
+ if (d[i].id == obj.id) {
696
+ d.splice(i, 1, Object.assign(d[i],obj));
697
+ break;
698
+ }
699
+ }
700
+ M.writeObjToFile(file, d);
701
+ }
702
+ M.getObjByIdFile = function (file, id) {
703
+ var d = M.getObjByFile(file);
704
+ for (let i = 0; i < d.length; i++) {
705
+ if (d[i].id == id) {
706
+ return d[i];
707
+ }
708
+ }
709
+ }
710
+ M.listAllObjByPropFile = function (file, caseObj) {
711
+ var d = M.getObjByFile(file);
712
+ let o_keys = Object.keys(caseObj);
713
+ if (caseObj && o_keys.length>0) {
714
+ let r_list = [];
715
+ let o_vals = Object.values(caseObj);
716
+ for (let i = 0; i < d.length; i++) {
717
+ let s=0;
718
+ for (let j=0;j<o_keys.length;j++){
719
+ if (d[i][o_keys[j]] != o_vals[j]) {
720
+ break
721
+ }
722
+ s++;
723
+ }
724
+ if(s==o_keys.length){
725
+ r_list.push(d[i]);
726
+ }
727
+ }
728
+ return r_list;
729
+ } else {
730
+ return d;
731
+ }
732
+ }
733
+ /**
734
+ * 文件型数据库第二层封装
735
+ */
736
+ M.add = function (obj) {
737
+ obj.id = M.randomStr();
738
+ M.addObjToFile(M.database_path, obj);
739
+ return obj;
740
+ }
741
+ M.update = function (obj) {
742
+ M.updateObjByIdFile(M.database_path, obj);
743
+ }
744
+ M.deleteById = function (id) {
745
+ M.deleteObjByIdFile(M.database_path, id);
746
+ }
747
+ M.deleteAll = function (o) {
748
+ if (o) {
749
+ M.deleteObjByPropFile(M.database_path, o);
750
+ } else {
751
+ M.writeObjToFile(M.database_path, []);
752
+ }
753
+ }
754
+ M.deleteByProp = function (o) {
755
+ M.deleteObjByPropFile(M.database_path, o);
756
+ }
757
+ M.getById = function (id) {
758
+ return M.getObjByIdFile(M.database_path, id);
759
+ }
760
+ M.listAll = function (o) {
761
+ if (o) {
762
+ return M.listAllObjByPropFile(M.database_path, o);
763
+ } else {
764
+ return M.getObjByFile(M.database_path);
765
+ }
766
+ }
767
+ M.listByProp = function (o) {
768
+ return M.listAllObjByPropFile(M.database_path, o);
769
+ }
770
+ M.listByPage = function (startPage, limit, caseObj) {
771
+ if (startPage <= 0) startPage = 1;
772
+ let rows;
773
+ if (caseObj) {
774
+ rows = M.listByProp(caseObj);
775
+ } else {
776
+ rows = M.listAll();
777
+ }
778
+ let total = rows.length;
779
+ rows = rows.splice((startPage - 1) * limit, limit)
780
+ return {rows, total}
781
+ }
782
+ /**
783
+ * 全局作用域
784
+ * @param k
785
+ * @param v
786
+ */
787
+ M.setAttribute = function (k, v) {
788
+ let a = {}
789
+ a[k] = v;
790
+ a = JSON.stringify(a)
791
+ a = JSON.parse(a);
792
+ let preObj;
793
+ try {
794
+ preObj = M.getObjByFile(M.map_path);
795
+ if (Array.isArray(preObj)) preObj = {};
796
+ } catch (e) {
797
+ preObj = {};
798
+ }
799
+
800
+ M.writeObjToFile(M.map_path, Object.assign(preObj, a));
801
+ }
802
+
803
+ M.getAttribute = function (k) {
804
+ return M.getObjByFile(M.map_path)[k];
805
+ }
806
+ /**
807
+ *逐行读取文件
808
+ */
809
+ M.readLine =async function (file, callback) {
810
+ let lineCount=0;
811
+ return new Promise((resolve, reject) =>{
812
+ var remaining = '';
813
+ var input = fs.createReadStream(file);
814
+ input.on('data', function (data) {
815
+ remaining += data;
816
+ var index = remaining.indexOf('\n');
817
+ while (index > -1) {
818
+ var line = remaining.substring(0, index);
819
+ remaining = remaining.substring(index + 1);
820
+ lineCount++;
821
+ callback(line);
822
+ index = remaining.indexOf('\n');
823
+ }
824
+ });
825
+ input.on('end', function () {
826
+ if (remaining.length > 0) {
827
+ resolve(lineCount);
828
+ callback(remaining);
829
+ }
830
+ });
831
+ } )
832
+ }
833
+
834
+
835
+ M.readCsvLine =async function (file, callback) {
821
836
  return M.readLine(file, function (line) {
822
- callback(line.replace("\r", "").split(/(?<!\"[^,]+),(?![^,]+\")/));
823
- })
824
- }
825
-
826
- M.getFileNameByUrl=function (url){
827
- let split= url.split("/");
828
- return split[split.length-1]
829
- }
837
+ callback(line.replace("\r", "").split(/(?<!\"[^,]+),(?![^,]+\")/));
838
+ })
839
+ }
840
+
841
+ M.getFileNameByUrl=function (url){
842
+ let split= url.split("/");
843
+ return split[split.length-1]
844
+ }
830
845
 
831
846
  M.getFileList = function (path) {
832
- //遍历读取文件
833
- function readFile(path, filesList, targetObj) {
834
- files = fs.readdirSync(path);//需要用到同步读取
835
- files.forEach(walk);
836
-
837
- function walk(file) {
838
- states = fs.statSync(path + '/' + file);
839
- if (states.isDirectory()) {
840
- var item;
841
- if (targetObj["children"]) {
842
- item = {name: file, children: [], value: path + '/' + file};
843
- targetObj["children"].push(item);
844
- } else {
845
- item = {name: file, children: [], value: path + '/' + file};
846
- filesList.push(item);
847
- }
848
-
849
- readFile(path + '/' + file, filesList, item);
850
- } else {
851
- //创建一个对象保存信息
852
- var obj = new Object();
853
- obj.size = states.size;//文件大小,以字节为单位
854
- obj.name = file;//文件名
855
- obj.path = path + '/' + file; //文件绝对路径
856
-
857
- if (targetObj["children"]) {
858
- var item = {name: file, value: obj.path}
859
- targetObj["children"].push(item);
860
- } else {
861
- var item = {name: file, value: obj.path};
862
- filesList.push(item);
863
- }
864
- }
865
- }
866
- }
867
-
868
- var filesList = [];
869
- var targetObj = {};
870
- readFile(path, filesList, targetObj);
871
- return filesList;
872
- }
847
+ //遍历读取文件
848
+ function readFile(path, filesList, targetObj) {
849
+ files = fs.readdirSync(path);//需要用到同步读取
850
+ files.forEach(walk);
851
+
852
+ function walk(file) {
853
+ states = fs.statSync(path + '/' + file);
854
+ if (states.isDirectory()) {
855
+ var item;
856
+ if (targetObj["children"]) {
857
+ item = {name: file, children: [], value: path + '/' + file};
858
+ targetObj["children"].push(item);
859
+ } else {
860
+ item = {name: file, children: [], value: path + '/' + file};
861
+ filesList.push(item);
862
+ }
863
+
864
+ readFile(path + '/' + file, filesList, item);
865
+ } else {
866
+ //创建一个对象保存信息
867
+ var obj = new Object();
868
+ obj.size = states.size;//文件大小,以字节为单位
869
+ obj.name = file;//文件名
870
+ obj.path = path + '/' + file; //文件绝对路径
871
+
872
+ if (targetObj["children"]) {
873
+ var item = {name: file, value: obj.path}
874
+ targetObj["children"].push(item);
875
+ } else {
876
+ var item = {name: file, value: obj.path};
877
+ filesList.push(item);
878
+ }
879
+ }
880
+ }
881
+ }
882
+
883
+ var filesList = [];
884
+ var targetObj = {};
885
+ readFile(path, filesList, targetObj);
886
+ return filesList;
887
+ }
873
888
 
874
889
  M.getFileDirList = function (path) {
875
890
  //遍历读取文件
@@ -927,63 +942,63 @@ M.watchFile=function (watch,callback) {
927
942
 
928
943
 
929
944
  M.log = function (...params) {
930
- if (Array.isArray(params[0]) || typeof params[0] == 'object') {
931
- params = [JSON.stringify(params[0])]
932
- }
933
- if (M.log_file_enable || M.log_console_enable) {
934
- let r = "";
935
- if (M.log_display_time) {
936
- r = r + new Date().toLocaleString() + " ";
937
- }
938
- for (i in params) {
939
- r = r + params[i] + " ";
940
- }
941
- if (M.log_console_enable) console.log(r);
942
- r = r + "\n";
943
- if (M.log_file_enable) M.appendFile(M.log_path, r);
944
- }
945
- }
946
-
947
-
948
- M.getSqlite = function (dbName) {
949
- if (M.sqlite) {
950
- return M.sqlite;
951
- }
952
- var SQLite3 = require('sqlite3').verbose();
953
- var Db = new SQLite3.Database(dbName || "ming_autotest.db");
954
- Db.doSql = function doSql(sql) {
955
- var promise = new Promise(function (reslove, reject) {
956
- if (Db.display_sql_enable) {
957
- M.log(sql)
958
- }
959
- if (sql.indexOf("select") > -1) {
960
- Db.all(sql,
961
- function (err, result) {
962
- if (err) {
963
- M.log(err);
964
- reject(err);
965
- } else {
966
- reslove(result);
967
- }
968
- });
969
- } else {
970
- Db.run(sql,
971
- function (err) {
972
- if (err) {
973
- // M.log(err);
974
- reject(err);
975
- }
976
- reslove(null);
977
- });
978
- }
979
- })
980
- return promise;
981
- }
982
- M.sqlite = Db;
983
- return Db;
984
- }
985
-
986
- ///////////////////////////////
945
+ if (Array.isArray(params[0]) || typeof params[0] == 'object') {
946
+ params = [JSON.stringify(params[0])]
947
+ }
948
+ if (M.log_file_enable || M.log_console_enable) {
949
+ let r = "";
950
+ if (M.log_display_time) {
951
+ r = r + new Date().toLocaleString() + " ";
952
+ }
953
+ for (i in params) {
954
+ r = r + params[i] + " ";
955
+ }
956
+ if (M.log_console_enable) console.log(r);
957
+ r = r + "\n";
958
+ if (M.log_file_enable) M.appendFile(M.log_path, r);
959
+ }
960
+ }
961
+
962
+
963
+ M.getSqlite = function (dbName) {
964
+ if (M.sqlite) {
965
+ return M.sqlite;
966
+ }
967
+ var SQLite3 = require('sqlite3').verbose();
968
+ var Db = new SQLite3.Database(dbName || "ming_autotest.db");
969
+ Db.doSql = function doSql(sql) {
970
+ var promise = new Promise(function (reslove, reject) {
971
+ if (Db.display_sql_enable) {
972
+ M.log(sql)
973
+ }
974
+ if (sql.indexOf("select") > -1) {
975
+ Db.all(sql,
976
+ function (err, result) {
977
+ if (err) {
978
+ M.log(err);
979
+ reject(err);
980
+ } else {
981
+ reslove(result);
982
+ }
983
+ });
984
+ } else {
985
+ Db.run(sql,
986
+ function (err) {
987
+ if (err) {
988
+ // M.log(err);
989
+ reject(err);
990
+ }
991
+ reslove(null);
992
+ });
993
+ }
994
+ })
995
+ return promise;
996
+ }
997
+ M.sqlite = Db;
998
+ return Db;
999
+ }
1000
+
1001
+ ///////////////////////////////
987
1002
 
988
1003
 
989
1004
  M.getMySql = function (dbConfig) {
@@ -1087,262 +1102,262 @@ M.getMySql = function (dbConfig) {
1087
1102
 
1088
1103
 
1089
1104
  M.getMongoDB = function (dbConfig) {
1090
- if (M.mongoDb) {
1091
- return M.mongoDb;
1092
- }
1093
- var MongoDB=require('mongodb');
1094
- var MongoClient =MongoDB.MongoClient;
1095
- const ObjectID = MongoDB.ObjectID;
1096
-
1097
- var Config={
1098
- dbUrl: dbConfig.dbUrl|| 'mongodb://localhost:27017/',
1099
- dbName: dbConfig.dbName|| 'miapi'
1100
- };
1101
-
1102
- class MingMongoClient{
1103
- static connect(){
1104
- return new Promise((resolve,reject)=>{
1105
- if(!MingMongoClient.dbClient){
1106
- console.log("connect mongodb", Config)
1107
- MongoClient.connect(Config.dbUrl,(err,client)=>{
1108
- if(err){
1109
- reject(err)
1110
- }else{
1111
- MingMongoClient.dbClient=client.db(Config.dbName);
1112
- resolve(MingMongoClient.dbClient)
1113
- }
1114
- })
1115
- }else{
1116
- resolve(MingMongoClient.dbClient);
1117
- }
1118
- })
1119
- }
1120
-
1121
- static find(collectionName,json){
1122
- if(!json){
1123
- json=collectionName
1124
- collectionName= MingMongoClient.collectionName;
1125
- }
1126
- return new Promise((resolve,reject)=>{
1127
- MingMongoClient.connect().then((db)=>{
1128
- var result=db.collection(collectionName).find(json);
1129
- result.toArray(function(err,docs){
1130
- if(err){
1131
- reject(err);
1132
- return;
1133
- }
1134
- resolve(docs);
1135
- })
1136
-
1137
- })
1138
- })
1139
- }
1140
- static update(collectionName,whereObj,updateObj){
1141
- if(!updateObj){
1142
- updateObj=whereObj;
1143
- whereObj=collectionName
1144
- collectionName= MingMongoClient.collectionName;
1145
- }
1146
- return new Promise((resolve,reject)=>{
1147
- MingMongoClient.connect().then((db)=>{
1148
- db.collection(collectionName).updateOne(whereObj,{
1149
- $set:updateObj
1150
- },(err,result)=>{
1151
- if(err){
1152
- reject(err);
1153
- }else{
1154
- resolve(result);
1155
- }
1156
- })
1157
- })
1158
- })
1159
- }
1160
- static insert(collectionName,json){
1161
- if(!json){
1162
- json=collectionName
1163
- collectionName= MingMongoClient.collectionName;
1164
- }
1165
- return new Promise((resolve,reject)=>{
1166
- MingMongoClient.connect().then((db)=>{
1167
- db.collection(collectionName).insertOne(json,function(err,result){
1168
- if(err){
1169
- reject(err);
1170
- }else{
1171
-
1172
- resolve(result);
1173
- }
1174
- })
1175
- })
1176
- })
1177
- }
1178
-
1179
- static insertMany(collectionName,json){
1180
- if(!json){
1181
- json=collectionName
1182
- collectionName= MingMongoClient.collectionName;
1183
- }
1184
- return new Promise((resolve,reject)=>{
1185
- MingMongoClient.connect().then((db)=>{
1186
- db.collection(collectionName).insertMany(json,function(err,result){
1187
- if(err){
1188
- reject(err);
1189
- }else{
1190
-
1191
- resolve(result);
1192
- }
1193
- })
1194
- })
1195
- })
1196
- }
1197
-
1198
- static remove(collectionName,json){
1199
- if(!json){
1200
- json=collectionName
1201
- collectionName= MingMongoClient.collectionName;
1202
- }
1203
- return new Promise((resolve,reject)=>{
1204
- MingMongoClient.connect().then((db)=>{
1205
- db.collection(collectionName).removeOne(json,function(err,result){
1206
- if(err){
1207
- reject(err);
1208
- }else{
1209
-
1210
- resolve(result);
1211
- }
1212
- })
1213
- })
1214
- })
1215
- }
1216
-
1217
- static getById(collectionName,id){
1218
- if(!id){
1219
- id=collectionName
1220
- collectionName= MingMongoClient.collectionName;
1221
- }
1222
- return new Promise((resolve,reject)=>{
1223
- MingMongoClient.connect().then((db)=>{
1224
- var whereArgs = {
1225
- _id: new ObjectID(id)
1226
- };
1227
- db.collection(collectionName).findOne(whereArgs,{},function(err,result){
1228
- if(err){
1229
- reject(err);
1230
- }else{
1231
- resolve(result);
1232
- }
1233
- })
1234
- })
1235
- })
1236
- }
1237
-
1238
- }
1239
- MingMongoClient.ObjectID=(id)=> new ObjectID(id)
1240
- let Db=MingMongoClient;
1241
- Db.dbConfig=Config;
1242
- MingMongoClient.collectionName="test"
1243
- M.mongoDb=Db;
1244
- return Db;
1245
- }
1246
-
1247
-
1248
-
1249
- /**
1250
- * ----------------------Sql CRUD START-------------------------------------------
1251
- */
1252
- M.getInsertObjSql = function (tableName, obj) {
1253
- var fields = "(";
1254
- var values = "(";
1255
- for (let field in obj) {
1256
- fields += field + ",";
1257
- values += `'${obj[field]}'` + ",";
1258
- }
1259
- fields = fields.substr(0, fields.lastIndexOf(","));
1260
- values = values.substr(0, values.lastIndexOf(","));
1261
- fields += ")";
1262
- values += ")";
1263
- let sql = "insert into " + tableName + fields + " values " + values;
1264
- return sql;
1265
- }
1266
-
1267
- M.getDeleteObjSql = function (tableName, obj) {
1268
- var fields = [];
1269
- for (let field in obj) {
1270
- fields.push(field);
1271
- }
1272
- let sql = `delete from ${tableName} where ${fields.map(u => u + "='" + obj[u] + "'")}`;
1273
- sql = sql.replace(/,/g, " and ")
1274
- return sql;
1275
- }
1276
-
1277
- M.getUpdateObjSql = function (tableName, obj, caseObj) {
1278
- var fields = [];
1279
- for (let field in obj) {
1280
- if (field != "id")
1281
- fields.push(field);
1282
- }
1283
- let sql = "";
1284
- if (!caseObj) {
1285
- sql = `update ${tableName} set ${fields.map(u => u + "='" + obj[u] + "'")} where id=${obj.id}`;
1286
- } else {
1287
- var caseObjfields = [];
1288
- for (let caseObjfield in caseObj) {
1289
- caseObjfields.push(caseObjfield)
1290
- }
1291
- sql = `update ${tableName} set ${fields.map(u => u + "='" + obj[u] + "'")} where ${caseObjfields.map(u => u + "='" + caseObj[u] + "'").join(" and ")}`;
1292
- }
1293
-
1294
- return sql;
1295
- }
1296
-
1297
-
1298
- M.getSelectObjSql = function (tableName, obj) {
1299
- var fields = [];
1300
- for (let field in obj) {
1301
- fields.push(field);
1302
- }
1303
- let sql = `select * from ${tableName} where ${fields.map(u => u + "='" + obj[u] + "'")}`;
1304
- sql = sql.replace(/,/g, " and ")
1305
- return sql;
1306
- }
1307
-
1308
- /**
1309
- * ----------------------Sql CRUD START-------------------------------------------
1310
- */
1311
-
1312
-
1313
- /**
1314
- * ----------------------数据持久化读写END--------------------------------------------
1315
- */
1316
-
1317
-
1318
- /**
1319
- * ----------------------服务器端START--------------------------------------------
1320
- */
1321
- /**
1322
- *封装返回数据
1323
- */
1324
- M.result = function (data, success,message) {
1325
- var r = {};
1326
- if (success == false) {
1327
- r.code = -2;
1328
- r.msg = message||"操作失败";
1329
- } else {
1330
- r.code = 0;
1331
- r.msg = message||"success"
1332
- }
1333
- r.requestId=M.req? M.req.requestId:"";
1334
- try {
1335
- var obj = JSON.parse(data);
1336
- if (typeof obj == 'object' && obj) {
1337
- r.data = obj;
1338
- } else {
1339
- r.data = data;
1340
- }
1341
- } catch (e) {
1342
- r.data = data;
1343
- }
1344
- return JSON.stringify(r);
1345
- }
1105
+ if (M.mongoDb) {
1106
+ return M.mongoDb;
1107
+ }
1108
+ var MongoDB=require('mongodb');
1109
+ var MongoClient =MongoDB.MongoClient;
1110
+ const ObjectID = MongoDB.ObjectID;
1111
+
1112
+ var Config={
1113
+ dbUrl: dbConfig.dbUrl|| 'mongodb://localhost:27017/',
1114
+ dbName: dbConfig.dbName|| 'miapi'
1115
+ };
1116
+
1117
+ class MingMongoClient{
1118
+ static connect(){
1119
+ return new Promise((resolve,reject)=>{
1120
+ if(!MingMongoClient.dbClient){
1121
+ console.log("connect mongodb", Config)
1122
+ MongoClient.connect(Config.dbUrl,(err,client)=>{
1123
+ if(err){
1124
+ reject(err)
1125
+ }else{
1126
+ MingMongoClient.dbClient=client.db(Config.dbName);
1127
+ resolve(MingMongoClient.dbClient)
1128
+ }
1129
+ })
1130
+ }else{
1131
+ resolve(MingMongoClient.dbClient);
1132
+ }
1133
+ })
1134
+ }
1135
+
1136
+ static find(collectionName,json){
1137
+ if(!json){
1138
+ json=collectionName
1139
+ collectionName= MingMongoClient.collectionName;
1140
+ }
1141
+ return new Promise((resolve,reject)=>{
1142
+ MingMongoClient.connect().then((db)=>{
1143
+ var result=db.collection(collectionName).find(json);
1144
+ result.toArray(function(err,docs){
1145
+ if(err){
1146
+ reject(err);
1147
+ return;
1148
+ }
1149
+ resolve(docs);
1150
+ })
1151
+
1152
+ })
1153
+ })
1154
+ }
1155
+ static update(collectionName,whereObj,updateObj){
1156
+ if(!updateObj){
1157
+ updateObj=whereObj;
1158
+ whereObj=collectionName
1159
+ collectionName= MingMongoClient.collectionName;
1160
+ }
1161
+ return new Promise((resolve,reject)=>{
1162
+ MingMongoClient.connect().then((db)=>{
1163
+ db.collection(collectionName).updateOne(whereObj,{
1164
+ $set:updateObj
1165
+ },(err,result)=>{
1166
+ if(err){
1167
+ reject(err);
1168
+ }else{
1169
+ resolve(result);
1170
+ }
1171
+ })
1172
+ })
1173
+ })
1174
+ }
1175
+ static insert(collectionName,json){
1176
+ if(!json){
1177
+ json=collectionName
1178
+ collectionName= MingMongoClient.collectionName;
1179
+ }
1180
+ return new Promise((resolve,reject)=>{
1181
+ MingMongoClient.connect().then((db)=>{
1182
+ db.collection(collectionName).insertOne(json,function(err,result){
1183
+ if(err){
1184
+ reject(err);
1185
+ }else{
1186
+
1187
+ resolve(result);
1188
+ }
1189
+ })
1190
+ })
1191
+ })
1192
+ }
1193
+
1194
+ static insertMany(collectionName,json){
1195
+ if(!json){
1196
+ json=collectionName
1197
+ collectionName= MingMongoClient.collectionName;
1198
+ }
1199
+ return new Promise((resolve,reject)=>{
1200
+ MingMongoClient.connect().then((db)=>{
1201
+ db.collection(collectionName).insertMany(json,function(err,result){
1202
+ if(err){
1203
+ reject(err);
1204
+ }else{
1205
+
1206
+ resolve(result);
1207
+ }
1208
+ })
1209
+ })
1210
+ })
1211
+ }
1212
+
1213
+ static remove(collectionName,json){
1214
+ if(!json){
1215
+ json=collectionName
1216
+ collectionName= MingMongoClient.collectionName;
1217
+ }
1218
+ return new Promise((resolve,reject)=>{
1219
+ MingMongoClient.connect().then((db)=>{
1220
+ db.collection(collectionName).removeOne(json,function(err,result){
1221
+ if(err){
1222
+ reject(err);
1223
+ }else{
1224
+
1225
+ resolve(result);
1226
+ }
1227
+ })
1228
+ })
1229
+ })
1230
+ }
1231
+
1232
+ static getById(collectionName,id){
1233
+ if(!id){
1234
+ id=collectionName
1235
+ collectionName= MingMongoClient.collectionName;
1236
+ }
1237
+ return new Promise((resolve,reject)=>{
1238
+ MingMongoClient.connect().then((db)=>{
1239
+ var whereArgs = {
1240
+ _id: new ObjectID(id)
1241
+ };
1242
+ db.collection(collectionName).findOne(whereArgs,{},function(err,result){
1243
+ if(err){
1244
+ reject(err);
1245
+ }else{
1246
+ resolve(result);
1247
+ }
1248
+ })
1249
+ })
1250
+ })
1251
+ }
1252
+
1253
+ }
1254
+ MingMongoClient.ObjectID=(id)=> new ObjectID(id)
1255
+ let Db=MingMongoClient;
1256
+ Db.dbConfig=Config;
1257
+ MingMongoClient.collectionName="test"
1258
+ M.mongoDb=Db;
1259
+ return Db;
1260
+ }
1261
+
1262
+
1263
+
1264
+ /**
1265
+ * ----------------------Sql CRUD START-------------------------------------------
1266
+ */
1267
+ M.getInsertObjSql = function (tableName, obj) {
1268
+ var fields = "(";
1269
+ var values = "(";
1270
+ for (let field in obj) {
1271
+ fields += field + ",";
1272
+ values += `'${obj[field]}'` + ",";
1273
+ }
1274
+ fields = fields.substr(0, fields.lastIndexOf(","));
1275
+ values = values.substr(0, values.lastIndexOf(","));
1276
+ fields += ")";
1277
+ values += ")";
1278
+ let sql = "insert into " + tableName + fields + " values " + values;
1279
+ return sql;
1280
+ }
1281
+
1282
+ M.getDeleteObjSql = function (tableName, obj) {
1283
+ var fields = [];
1284
+ for (let field in obj) {
1285
+ fields.push(field);
1286
+ }
1287
+ let sql = `delete from ${tableName} where ${fields.map(u => u + "='" + obj[u] + "'")}`;
1288
+ sql = sql.replace(/,/g, " and ")
1289
+ return sql;
1290
+ }
1291
+
1292
+ M.getUpdateObjSql = function (tableName, obj, caseObj) {
1293
+ var fields = [];
1294
+ for (let field in obj) {
1295
+ if (field != "id")
1296
+ fields.push(field);
1297
+ }
1298
+ let sql = "";
1299
+ if (!caseObj) {
1300
+ sql = `update ${tableName} set ${fields.map(u => u + "='" + obj[u] + "'")} where id=${obj.id}`;
1301
+ } else {
1302
+ var caseObjfields = [];
1303
+ for (let caseObjfield in caseObj) {
1304
+ caseObjfields.push(caseObjfield)
1305
+ }
1306
+ sql = `update ${tableName} set ${fields.map(u => u + "='" + obj[u] + "'")} where ${caseObjfields.map(u => u + "='" + caseObj[u] + "'").join(" and ")}`;
1307
+ }
1308
+
1309
+ return sql;
1310
+ }
1311
+
1312
+
1313
+ M.getSelectObjSql = function (tableName, obj) {
1314
+ var fields = [];
1315
+ for (let field in obj) {
1316
+ fields.push(field);
1317
+ }
1318
+ let sql = `select * from ${tableName} where ${fields.map(u => u + "='" + obj[u] + "'")}`;
1319
+ sql = sql.replace(/,/g, " and ")
1320
+ return sql;
1321
+ }
1322
+
1323
+ /**
1324
+ * ----------------------Sql CRUD START-------------------------------------------
1325
+ */
1326
+
1327
+
1328
+ /**
1329
+ * ----------------------数据持久化读写END--------------------------------------------
1330
+ */
1331
+
1332
+
1333
+ /**
1334
+ * ----------------------服务器端START--------------------------------------------
1335
+ */
1336
+ /**
1337
+ *封装返回数据
1338
+ */
1339
+ M.result = function (data, success,message) {
1340
+ var r = {};
1341
+ if (success == false) {
1342
+ r.code = -2;
1343
+ r.msg = message||"操作失败";
1344
+ } else {
1345
+ r.code = 0;
1346
+ r.msg = message||"success"
1347
+ }
1348
+ r.requestId=M.req? M.req.requestId:"";
1349
+ try {
1350
+ var obj = JSON.parse(data);
1351
+ if (typeof obj == 'object' && obj) {
1352
+ r.data = obj;
1353
+ } else {
1354
+ r.data = data;
1355
+ }
1356
+ } catch (e) {
1357
+ r.data = data;
1358
+ }
1359
+ return JSON.stringify(r);
1360
+ }
1346
1361
 
1347
1362
  M.successResult=(d,msg)=>{
1348
1363
  let r=d;
@@ -1362,30 +1377,30 @@ M.failResult=(msg,code,d)=>{
1362
1377
  }
1363
1378
 
1364
1379
  /**
1365
- *获取下划线式的对象
1366
- */
1367
- M.getUnderlineObj = function (obj) {
1368
- var result = {};
1369
- for (let field in obj) {
1370
- result[field.humpToUnderline()] = obj[field]
1371
- }
1372
- return result;
1373
- }
1374
-
1375
- /**
1376
- *获取驼峰式的对象
1377
- */
1378
- M.getHumpObj = function (obj) {
1379
- var result = {};
1380
- for (let field in obj) {
1381
- result[field.underlineToHump()] = obj[field]
1382
- }
1383
- return result;
1384
- }
1385
-
1386
- M.randomStr = function () {
1387
- return (Math.random().toString(36) + new Date().getTime()).slice(2);
1388
- }
1380
+ *获取下划线式的对象
1381
+ */
1382
+ M.getUnderlineObj = function (obj) {
1383
+ var result = {};
1384
+ for (let field in obj) {
1385
+ result[field.humpToUnderline()] = obj[field]
1386
+ }
1387
+ return result;
1388
+ }
1389
+
1390
+ /**
1391
+ *获取驼峰式的对象
1392
+ */
1393
+ M.getHumpObj = function (obj) {
1394
+ var result = {};
1395
+ for (let field in obj) {
1396
+ result[field.underlineToHump()] = obj[field]
1397
+ }
1398
+ return result;
1399
+ }
1400
+
1401
+ M.randomStr = function () {
1402
+ return (Math.random().toString(36) + new Date().getTime()).slice(2);
1403
+ }
1389
1404
 
1390
1405
  M.urlStringify = function (obj) {
1391
1406
  if (obj !== null && typeof obj === 'object') {
@@ -1420,459 +1435,461 @@ M.urlParse = function (url) {
1420
1435
  }
1421
1436
  return s
1422
1437
  };
1423
-
1424
- /**
1425
- * 异常处理钩子
1426
- * @param e
1427
- */
1428
- M.err = function (e) {
1429
- if (e) {
1430
- console.log(e.message);
1431
- return false;
1432
- }
1433
- return true;
1434
- }
1435
-
1436
-
1437
-
1438
- M.server = function () {
1439
- var G = this; /*全局变量,也就是M*/
1440
- //静态资源路径
1441
- this._views = "static";
1442
- //key为去除rest参数的url,val为原始url
1443
- this._rest = {};
1444
- //通配符
1445
- this._use = {};
1446
- //处理get和post请求
1447
- this._get = {};
1448
- this._post = {};
1449
- this._put = {};
1450
- this._delete = {};
1451
- this._mapping = {};
1452
- //用于模拟过滤器
1453
- this._begin = function () {
1454
- }
1455
- //服务器响应后的钩子函数
1456
- this._end = function () {
1457
- }
1458
- //如果实现此函数,则只能有一个此服务
1459
- this._server = function () {
1460
- };
1461
- var app =async function (req, res) {
1462
- try {
1463
- M.req=req;
1464
- M.res=res;
1465
- //是否已经发送过了
1466
- res.alreadySend = false;
1467
- req.requestId=M.randomStr();
1468
- //是否为静态资源请求
1469
- req.isStaticRequest = function () {
1470
- if (req.url.indexOf("?") > 0) {
1471
- return privateObj.staticMime[path.extname(req.url.substr(0, req.url.indexOf("?")))];
1472
- } else {
1473
- return privateObj.staticMime[path.extname(req.url)];
1474
- }
1475
- }
1476
- //是否为rest请求
1477
- req.isRestRequest = function () {
1478
- if (Object.keys(G._rest).length == 0) return false;
1479
- var isRest = false;
1480
- for (let i = 0; i < Object.keys(G._rest).length; i++) {
1481
- if (pathname.startsWith(Object.keys(G._rest)[i])) {
1482
- isRest = true;
1483
- break;
1484
- }
1485
- }
1486
- return isRest;
1487
- }
1488
-
1489
- req.ip = req.headers['x-forwarded-for'] ||
1490
- req.connection.remoteAddress ||
1491
- req.socket.remoteAddress ||
1492
- req.connection.socket.remoteAddress;
1493
- //请求cookies封装
1494
- req.cookies = querystring.parse(req.headers['cookie'], "; ");
1495
- //设置浏览器cookies
1496
- res.cookie = function (key, value, cfg) {
1497
- let o = {}
1498
- o[key] = value;
1499
- let r_cookie = Object.assign(o, cfg)
1500
- res.setHeader("Set-Cookie", querystring.stringify(r_cookie, " ;"));
1501
- }
1502
- if (true) {
1503
- Object.defineProperty(req, 'session', {
1504
- set: function (o) {
1505
- let sessionValue = req.cookies.sessionid || M.randomStr();
1506
- res.cookie("sessionid", sessionValue)
1507
- M.sessions[sessionValue] = o;
1508
- },
1509
- get: function () {
1510
- return M.sessions[req.cookies.sessionid]
1511
- },
1512
- configurable: true
1513
- })
1514
- }
1515
- //扩充res一个send方法
1516
- res.send = function (data) {
1517
- res.alreadySend = true;
1518
- let isString = "[object String]" === Object.prototype.toString.call(data)
1519
- if (!isString) {
1520
- data = JSON.stringify(data);
1521
- }
1522
- let requestOrigin = "*";
1523
- if (req.headers["origin"]) {
1524
- requestOrigin = req.headers["origin"];
1525
- }
1526
- let requestHeaders = "X-Requested-With";
1527
- if (req.headers['access-control-request-headers']) {
1528
- requestHeaders = req.headers['access-control-request-headers'];
1529
- }
1530
- res.setHeader("Access-Control-Allow-Origin", requestOrigin);
1531
- res.setHeader("Access-Control-Allow-Headers", requestHeaders);
1532
- res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
1533
- res.setHeader("Access-Control-Allow-Credentials", "true");
1534
- res.setHeader("X-Powered-By", ' 3.2.1')
1535
- res.setHeader("Content-Type", "application/json;charset=utf-8");
1536
- res.end(data);
1537
- G._end(req,data);
1538
- }
1539
- //扩充res一个renderByUrl方法
1540
- res.renderUrl = async function (url) {
1541
- res.alreadySend = true;
1542
- let text="";
1543
- if(!url.startsWith("http")&&!url.startsWith("file")){
1544
- if(!url.startsWith("/")){
1545
- url="/"+url;
1546
- }
1547
- url=G["_views"]+url;
1548
- text = M.readFile(url);
1549
- }else {
1550
- text = await M.getRemoteCacheByUrl(url)
1551
- }
1552
- let isString = "[object String]" === Object.prototype.toString.call(text)
1553
- if (!isString) {
1554
- text = JSON.stringify(text);
1555
- }
1556
- var pathname = url_module.parse(url).pathname; /*获取url的值*/
1557
- //获取文件的后缀名
1558
- var extname = path.extname(pathname);
1559
- res.writeHead(200, {"Content-Type": "" + (privateObj.staticMime[extname] || 'text/html') + ";charset='utf-8'",});
1560
- res.write(text);
1561
- res.end();
1562
- G._end(req,text);
1563
- }
1564
-
1565
- res.render = async function (url) {
1566
- res.alreadySend = true;
1567
- let text="";
1568
- if(!url.startsWith("http")&&!url.startsWith("file")){
1569
- if(!url.startsWith("/")){
1570
- url="/"+url;
1571
- }
1572
- url=G["_views"]+url;
1573
- text = M.readFile(url);
1574
- }else {
1575
- text = await M.getRemoteCacheByUrl(url)
1576
- }
1577
- let isString = "[object String]" === Object.prototype.toString.call(text)
1578
- if (!isString) {
1579
- text = JSON.stringify(text);
1580
- }
1581
- var pathname = url_module.parse(url).pathname; /*获取url的值*/
1582
- //获取文件的后缀名
1583
- var extname = path.extname(pathname);
1584
- res.writeHead(200, {"Content-Type": "" + (privateObj.staticMime[extname] || 'text/html') + ";charset='utf-8'",});
1585
- let templateStr=""
1586
- try {
1587
- templateStr= M.template(text)
1588
- }catch (e){
1438
+
1439
+ /**
1440
+ * 异常处理钩子
1441
+ * @param e
1442
+ */
1443
+ M.err = function (e) {
1444
+ if (e) {
1445
+ console.log(e.message);
1446
+ return false;
1447
+ }
1448
+ return true;
1449
+ }
1450
+
1451
+
1452
+
1453
+ M.server = function () {
1454
+ var G = this; /*全局变量,也就是M*/
1455
+ //静态资源路径
1456
+ this._views = "static";
1457
+ //key为去除rest参数的url,val为原始url
1458
+ this._rest = {};
1459
+ //通配符
1460
+ this._use = {};
1461
+ //处理get和post请求
1462
+ this._get = {};
1463
+ this._post = {};
1464
+ this._put = {};
1465
+ this._delete = {};
1466
+ this._mapping = {};
1467
+ //用于模拟过滤器
1468
+ this._begin = function () {
1469
+ }
1470
+ //服务器响应后的钩子函数
1471
+ this._end = function () {
1472
+ }
1473
+ //如果实现此函数,则只能有一个此服务
1474
+ this._server = function () {
1475
+ };
1476
+ var app =async function (req, res) {
1477
+ try {
1478
+ M.req=req;
1479
+ M.res=res;
1480
+ //是否已经发送过了
1481
+ res.alreadySend = false;
1482
+ req.requestId=M.randomStr();
1483
+ //是否为静态资源请求
1484
+ req.isStaticRequest = function () {
1485
+ if (req.url.indexOf("?") > 0) {
1486
+ return privateObj.staticMime[path.extname(req.url.substr(0, req.url.indexOf("?")))];
1487
+ } else {
1488
+ return privateObj.staticMime[path.extname(req.url)];
1489
+ }
1490
+ }
1491
+ //是否为rest请求
1492
+ req.isRestRequest = function () {
1493
+ if (Object.keys(G._rest).length == 0) return false;
1494
+ var isRest = false;
1495
+ for (let i = 0; i < Object.keys(G._rest).length; i++) {
1496
+ if (pathname.startsWith(Object.keys(G._rest)[i])) {
1497
+ isRest = true;
1498
+ break;
1499
+ }
1500
+ }
1501
+ return isRest;
1502
+ }
1503
+
1504
+ req.ip = req.headers['x-forwarded-for'] ||
1505
+ req.connection.remoteAddress ||
1506
+ req.socket.remoteAddress ||
1507
+ req.connection.socket.remoteAddress;
1508
+ //请求cookies封装
1509
+ req.cookies = querystring.parse(req.headers['cookie'], "; ");
1510
+ //设置浏览器cookies
1511
+ res.cookie = function (key, value, cfg) {
1512
+ let o = {}
1513
+ o[key] = value;
1514
+ let r_cookie = Object.assign(o, cfg)
1515
+ let setCookies= querystring.stringify(r_cookie, " ;");
1516
+ setCookies= setCookies.replace(/%2F/g,'/');
1517
+ res.setHeader("Set-Cookie", setCookies);
1518
+ }
1519
+ if (true) {
1520
+ Object.defineProperty(req, 'session', {
1521
+ set: function (o) {
1522
+ let sessionValue = req.cookies.sessionid || M.randomStr();
1523
+ res.cookie("sessionid", sessionValue,{Path:"/"})
1524
+ M.sessions[sessionValue] = o;
1525
+ },
1526
+ get: function () {
1527
+ return M.sessions[req.cookies.sessionid]
1528
+ },
1529
+ configurable: true
1530
+ })
1531
+ }
1532
+ //扩充res一个send方法
1533
+ res.send = function (data) {
1534
+ res.alreadySend = true;
1535
+ let isString = "[object String]" === Object.prototype.toString.call(data)
1536
+ if (!isString) {
1537
+ data = JSON.stringify(data);
1538
+ }
1539
+ let requestOrigin = "*";
1540
+ if (req.headers["origin"]) {
1541
+ requestOrigin = req.headers["origin"];
1542
+ }
1543
+ let requestHeaders = "X-Requested-With";
1544
+ if (req.headers['access-control-request-headers']) {
1545
+ requestHeaders = req.headers['access-control-request-headers'];
1546
+ }
1547
+ res.setHeader("Access-Control-Allow-Origin", requestOrigin);
1548
+ res.setHeader("Access-Control-Allow-Headers", requestHeaders);
1549
+ res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
1550
+ res.setHeader("Access-Control-Allow-Credentials", "true");
1551
+ res.setHeader("X-Powered-By", ' 3.2.1')
1552
+ res.setHeader("Content-Type", "application/json;charset=utf-8");
1553
+ res.end(data);
1554
+ G._end(req,data);
1555
+ }
1556
+ //扩充res一个renderByUrl方法
1557
+ res.renderUrl = async function (url) {
1558
+ res.alreadySend = true;
1559
+ let text="";
1560
+ if(!url.startsWith("http")&&!url.startsWith("file")){
1561
+ if(!url.startsWith("/")){
1562
+ url="/"+url;
1563
+ }
1564
+ url=G["_views"]+url;
1565
+ text = M.readFile(url);
1566
+ }else {
1567
+ text = await M.getRemoteCacheByUrl(url)
1568
+ }
1569
+ let isString = "[object String]" === Object.prototype.toString.call(text)
1570
+ if (!isString) {
1571
+ text = JSON.stringify(text);
1572
+ }
1573
+ var pathname = url_module.parse(url).pathname; /*获取url的值*/
1574
+ //获取文件的后缀名
1575
+ var extname = path.extname(pathname);
1576
+ res.writeHead(200, {"Content-Type": "" + (privateObj.staticMime[extname] || 'text/html') + ";charset='utf-8'",});
1577
+ res.write(text);
1578
+ res.end();
1579
+ G._end(req,text);
1580
+ }
1581
+
1582
+ res.render = async function (url) {
1583
+ res.alreadySend = true;
1584
+ let text="";
1585
+ if(!url.startsWith("http")&&!url.startsWith("file")){
1586
+ if(!url.startsWith("/")){
1587
+ url="/"+url;
1588
+ }
1589
+ url=G["_views"]+url;
1590
+ text = M.readFile(url);
1591
+ }else {
1592
+ text = await M.getRemoteCacheByUrl(url)
1593
+ }
1594
+ let isString = "[object String]" === Object.prototype.toString.call(text)
1595
+ if (!isString) {
1596
+ text = JSON.stringify(text);
1597
+ }
1598
+ var pathname = url_module.parse(url).pathname; /*获取url的值*/
1599
+ //获取文件的后缀名
1600
+ var extname = path.extname(pathname);
1601
+ res.writeHead(200, {"Content-Type": "" + (privateObj.staticMime[extname] || 'text/html') + ";charset='utf-8'",});
1602
+ let templateStr=""
1603
+ try {
1604
+ templateStr= M.template(text)
1605
+ }catch (e){
1589
1606
  M["_render_exception_handle"](e,req,res);
1590
- }
1591
- if(templateStr){
1592
- text=templateStr;
1593
- }
1594
- res.write(text);
1595
- res.end();
1596
- G._end(req,text);
1597
- }
1598
- //扩充res一个renderJs方法
1599
- res.renderJs = function (text) {
1600
- res.alreadySend = true;
1601
- res.writeHead(200, {"Content-Type": "application/javascript"});
1602
- res.write(text);
1603
- res.end();
1604
- G._end(req,text);
1605
- }
1606
- //扩充res一个renderHtml方法
1607
- res.renderHtml = function (text) {
1608
- res.alreadySend = true;
1609
- res.writeHead(200, {"Content-Type": "text/html;charset='utf-8'"});
1610
- res.write(text);
1611
- res.end();
1612
- G._end(req,text);
1613
- }
1614
- res.redirect = function (url) {
1615
- res.alreadySend = true;
1616
- res.writeHead(302, {'Content-Type': 'text/html; charset=utf-8', 'Location': url});
1617
- res.end();
1618
- }
1619
- //获取路由
1620
- var pathname = url_module.parse(req.url).pathname;
1621
- if (!pathname.endsWith('/')) {
1622
- pathname = pathname + '/';
1623
- }
1624
- // pathname.startsWith("/usr/")
1625
- //获取请求的方式 get post
1626
- var method = req.method.toLowerCase();
1627
- if (req.isStaticRequest()) {
1628
-
1629
- await G._begin(req, res);
1630
- if (!res.alreadySend) await privateObj.dealUseServer(req, res);
1631
- if (!res.alreadySend) await privateObj.staticServer(req, res, G["_views"]);
1632
- } else {
1633
-
1634
- //为req加个params用于存放请求参数
1635
- req.params = {};
1636
- var mapingPath = "";
1637
- //如果是rest风格的请求,为其封装请求参数
1638
- if (req.isRestRequest()) {
1639
- for (let i = 0; i < Object.keys(G._rest).length; i++) {
1640
- if (pathname.startsWith(Object.keys(G._rest)[i])) {
1641
- pathname = Object.keys(G._rest)[i];
1642
- mapingPath = G._rest[pathname];
1643
- }
1644
- }
1645
- var realPathName = url_module.parse(req.url).pathname;
1646
- if (!realPathName.endsWith('/')) {
1647
- realPathName = realPathName + '/';
1648
- }
1649
- let s1 = realPathName;
1650
- let s2 = mapingPath;
1651
- s1 = s1.substring(s2.indexOf(":") - 1, s1.length - 1).split("/").slice(1)
1652
- s2 = s2.substring(s2.indexOf(":") - 1, s2.length - 1).split("/:").slice(1)
1653
- for (let i = 0; i < s2.length; i++) {
1654
- req.params[s2[i]] = s1[i];
1655
- }
1656
- }
1657
- /**
1658
- * 加queryParam参数
1659
- */
1660
- req.params = Object.assign(req.params, url_module.parse(req.url, true).query);
1661
-
1662
- if ((method == "get" ||
1663
- method == "post" ||
1664
- method == "put" ||
1665
- method == "delete"
1666
- ) && (G['_' + method][pathname])) {
1667
- if (method != 'get') { /*执行post请求*/
1668
- var postStr = '';
1669
- req.on('data', function (chunk) {
1670
- postStr += chunk;
1671
- })
1672
- req.on('end',async function (err, chunk) {
1673
- req.body = postStr; /*表示拿到post的值*/
1674
- postData = "";
1675
- try {
1676
- if(req.headers["content-type"].indexOf("application/json")>=0){
1677
- postData = JSON.parse(req.body);
1678
- }else {
1679
- postData = url_module.parse("?" + req.body, true).query;
1680
- }
1681
- } catch (e) {
1682
-
1683
- }
1684
- req.params = Object.assign(req.params, postData);
1685
- await G._begin(req, res);
1686
- if (!res.alreadySend) await privateObj.dealUseServer(req, res);
1687
- if (!res.alreadySend) await G['_' + method][pathname](req, res); /*执行方法*/
1688
- })
1689
- } else if (method == "get") { /*执行get请求*/
1690
- await G._begin(req, res);
1691
- if (!res.alreadySend) await privateObj.dealUseServer(req, res);
1692
- if (!res.alreadySend) await G['_' + method][pathname](req, res); /*执行方法*/
1693
- }
1694
- } else {
1695
- if (G['_mapping'][pathname]) {
1696
- await G._begin(req, res);
1697
- if (!res.alreadySend) await privateObj.dealUseServer(req, res);
1698
- if (!res.alreadySend) await G['_mapping'][pathname](req, res); /*执行方法*/
1699
- } else {
1700
- await G._begin(req, res);
1701
- if (!res.alreadySend) await privateObj.dealUseServer(req, res);
1702
- if (!res.alreadySend) await G._server(req, res);
1703
- if (!res.alreadySend) await G["_no_router_handle"](req,res);
1704
- }
1705
- }
1706
- }
1707
- } catch (e) {
1708
- console.error(e);
1709
- M["_gloable_exception_handle"](e,req,res);
1710
- }
1711
- }
1712
-
1713
-
1714
- app.begin = function (callback) {
1715
- G._begin = callback;
1716
- }
1717
-
1718
- app.end = function (callback) {
1719
- G._end = callback;
1720
- }
1721
- /**
1722
- *唯一服务的方法
1723
- */
1724
- app.server = function (callback) {
1725
- G._server = callback;
1726
- }
1727
- app.use=function (url,callback){
1728
- if(typeof url === 'function' || typeof url === 'object' ){
1729
- let plugin=url;
1730
- let args=callback;
1731
- if(plugin.installed){
1732
- return app;
1733
- }
1734
- if (typeof plugin === 'function') {
1735
- plugin(app, args);
1736
- } else {
1737
- plugin.install(app, args);
1738
- }
1739
- M._globle_plugin.add(plugin);
1740
- plugin.installed = true;
1741
- }else {
1742
- if (Array.isArray(url)) {
1743
- url.forEach(u=>{
1744
- let regExp=new RegExp(u)
1745
- G._use[u] = {url,regExp,callback};
1746
- })
1747
- } else {
1748
- let regExp=new RegExp(url)
1749
- G._use[url] = {url,regExp,callback};
1750
- }
1751
- }
1752
- return app;
1753
- }
1754
-
1755
- app.installPlugin=async function (pluginUrl,constructorParams,pluginParams){
1756
- if(M._globle_plugin_url_cacheMap[pluginUrl]){
1757
- return
1758
- }
1759
- M._globle_plugin_url_cacheMap[pluginUrl]=pluginUrl;
1760
- const Plugin= await M.require(pluginUrl);
1761
- const plugin= new Plugin(constructorParams);
1762
- app.use(plugin,pluginParams)
1763
- }
1764
-
1765
- /**
1766
- * 注册get请求
1767
- */
1768
- app.get = function (url, callback) {
1769
- url = M.formatUrl(url);
1770
- var realUrl = url;
1771
- if (url.indexOf(":") > 0) {
1772
- url = url.substr(0, url.indexOf(":"));
1773
- G._rest[url] = realUrl;
1774
- }
1775
-
1776
- G._get[url] = callback;
1777
- }
1778
- /**
1779
- *注册post请求
1780
- */
1781
- app.post = function (url, callback) {
1782
- url = M.formatUrl(url);
1783
- var realUrl = url;
1784
- if (url.indexOf(":") > 0) {
1785
- url = url.substr(0, url.indexOf(":"));
1786
- G._rest[url] = realUrl;
1787
- }
1788
- G._post[url] = callback;
1789
- }
1790
-
1791
- app.put = function (url, callback) {
1792
- url = M.formatUrl(url);
1793
- var realUrl = url;
1794
- if (url.indexOf(":") > 0) {
1795
- url = url.substr(0, url.indexOf(":"));
1796
- G._rest[url] = realUrl;
1797
- }
1798
- G._put[url] = callback;
1799
- }
1800
-
1801
- app.delete = function (url, callback) {
1802
- url = M.formatUrl(url);
1803
- var realUrl = url;
1804
- if (url.indexOf(":") > 0) {
1805
- url = url.substr(0, url.indexOf(":"));
1806
- G._rest[url] = realUrl;
1807
- }
1808
- G._delete[url] = callback;
1809
- }
1810
- /**
1811
- *注册任意请求方法的请求
1812
- */
1813
- app.mapping = function (url, callback) {
1814
- url = M.formatUrl(url);
1815
- var realUrl = url;
1816
- if (url.indexOf(":") > 0) {
1817
- url = url.substr(0, url.indexOf(":"));
1818
- G._rest[url] = realUrl;
1819
- }
1820
- G._mapping[url] = callback;
1821
- }
1822
-
1823
-
1824
- M.formatUrl = function (url) {
1825
- if (!url.endsWith('/')) {
1826
- url = url + '/';
1827
- }
1828
- if (!url.startsWith('/')) {
1829
- url = '/' + url;
1830
- }
1831
- return url;
1832
- }
1833
- /**
1834
- *转发
1835
- */
1836
- app.dispatch = function (url, req, res) {
1837
- req.url = url;
1838
- app(req, res);
1839
- }
1840
-
1841
- /**
1842
- *重定向
1843
- */
1844
- app.redirect = function (url, req, res) {
1845
- res.writeHead(302, {'Content-Type': 'text/html; charset=utf-8', 'Location': url});
1846
- res.end();
1847
- }
1848
-
1849
- app.set = function (k, v) {
1850
- M["_" + k] = v;
1851
- }
1852
-
1853
-
1854
- //全局异常钩子
1855
- app.set("gloable_exception_handle",(err,req,res)=>{
1856
- console.error(err.stack)
1857
- if (res && !res.alreadySend) {
1607
+ }
1608
+ if(templateStr){
1609
+ text=templateStr;
1610
+ }
1611
+ res.write(text);
1612
+ res.end();
1613
+ G._end(req,text);
1614
+ }
1615
+ //扩充res一个renderJs方法
1616
+ res.renderJs = function (text) {
1617
+ res.alreadySend = true;
1618
+ res.writeHead(200, {"Content-Type": "application/javascript"});
1619
+ res.write(text);
1620
+ res.end();
1621
+ G._end(req,text);
1622
+ }
1623
+ //扩充res一个renderHtml方法
1624
+ res.renderHtml = function (text) {
1625
+ res.alreadySend = true;
1626
+ res.writeHead(200, {"Content-Type": "text/html;charset='utf-8'"});
1627
+ res.write(text);
1628
+ res.end();
1629
+ G._end(req,text);
1630
+ }
1631
+ res.redirect = function (url) {
1632
+ res.alreadySend = true;
1633
+ res.writeHead(302, {'Content-Type': 'text/html; charset=utf-8', 'Location': url});
1634
+ res.end();
1635
+ }
1636
+ //获取路由
1637
+ var pathname = url_module.parse(req.url).pathname;
1638
+ if (!pathname.endsWith('/')) {
1639
+ pathname = pathname + '/';
1640
+ }
1641
+ // pathname.startsWith("/usr/")
1642
+ //获取请求的方式 get post
1643
+ var method = req.method.toLowerCase();
1644
+ if (req.isStaticRequest()) {
1645
+
1646
+ await G._begin(req, res);
1647
+ if (!res.alreadySend) await privateObj.dealUseServer(req, res);
1648
+ if (!res.alreadySend) await privateObj.staticServer(req, res, G["_views"]);
1649
+ } else {
1650
+
1651
+ //为req加个params用于存放请求参数
1652
+ req.params = {};
1653
+ var mapingPath = "";
1654
+ //如果是rest风格的请求,为其封装请求参数
1655
+ if (req.isRestRequest()) {
1656
+ for (let i = 0; i < Object.keys(G._rest).length; i++) {
1657
+ if (pathname.startsWith(Object.keys(G._rest)[i])) {
1658
+ pathname = Object.keys(G._rest)[i];
1659
+ mapingPath = G._rest[pathname];
1660
+ }
1661
+ }
1662
+ var realPathName = url_module.parse(req.url).pathname;
1663
+ if (!realPathName.endsWith('/')) {
1664
+ realPathName = realPathName + '/';
1665
+ }
1666
+ let s1 = realPathName;
1667
+ let s2 = mapingPath;
1668
+ s1 = s1.substring(s2.indexOf(":") - 1, s1.length - 1).split("/").slice(1)
1669
+ s2 = s2.substring(s2.indexOf(":") - 1, s2.length - 1).split("/:").slice(1)
1670
+ for (let i = 0; i < s2.length; i++) {
1671
+ req.params[s2[i]] = s1[i];
1672
+ }
1673
+ }
1674
+ /**
1675
+ * 加queryParam参数
1676
+ */
1677
+ req.params = Object.assign(req.params, url_module.parse(req.url, true).query);
1678
+
1679
+ if ((method == "get" ||
1680
+ method == "post" ||
1681
+ method == "put" ||
1682
+ method == "delete"
1683
+ ) && (G['_' + method][pathname])) {
1684
+ if (method != 'get') { /*执行post请求*/
1685
+ var postStr = '';
1686
+ req.on('data', function (chunk) {
1687
+ postStr += chunk;
1688
+ })
1689
+ req.on('end',async function (err, chunk) {
1690
+ req.body = postStr; /*表示拿到post的值*/
1691
+ postData = "";
1692
+ try {
1693
+ if(req.headers["content-type"].indexOf("application/json")>=0){
1694
+ postData = JSON.parse(req.body);
1695
+ }else {
1696
+ postData = url_module.parse("?" + req.body, true).query;
1697
+ }
1698
+ } catch (e) {
1699
+
1700
+ }
1701
+ req.params = Object.assign(req.params, postData);
1702
+ await G._begin(req, res);
1703
+ if (!res.alreadySend) await privateObj.dealUseServer(req, res);
1704
+ if (!res.alreadySend) await G['_' + method][pathname](req, res); /*执行方法*/
1705
+ })
1706
+ } else if (method == "get") { /*执行get请求*/
1707
+ await G._begin(req, res);
1708
+ if (!res.alreadySend) await privateObj.dealUseServer(req, res);
1709
+ if (!res.alreadySend) await G['_' + method][pathname](req, res); /*执行方法*/
1710
+ }
1711
+ } else {
1712
+ if (G['_mapping'][pathname]) {
1713
+ await G._begin(req, res);
1714
+ if (!res.alreadySend) await privateObj.dealUseServer(req, res);
1715
+ if (!res.alreadySend) await G['_mapping'][pathname](req, res); /*执行方法*/
1716
+ } else {
1717
+ await G._begin(req, res);
1718
+ if (!res.alreadySend) await privateObj.dealUseServer(req, res);
1719
+ if (!res.alreadySend) await G._server(req, res);
1720
+ if (!res.alreadySend) await G["_no_router_handle"](req,res);
1721
+ }
1722
+ }
1723
+ }
1724
+ } catch (e) {
1725
+ console.error(e);
1726
+ M["_gloable_exception_handle"](e,req,res);
1727
+ }
1728
+ }
1729
+
1730
+
1731
+ app.begin = function (callback) {
1732
+ G._begin = callback;
1733
+ }
1734
+
1735
+ app.end = function (callback) {
1736
+ G._end = callback;
1737
+ }
1738
+ /**
1739
+ *唯一服务的方法
1740
+ */
1741
+ app.server = function (callback) {
1742
+ G._server = callback;
1743
+ }
1744
+ app.use=function (url,callback){
1745
+ if(typeof url === 'function' || typeof url === 'object' ){
1746
+ let plugin=url;
1747
+ let args=callback;
1748
+ if(plugin.installed){
1749
+ return app;
1750
+ }
1751
+ if (typeof plugin === 'function') {
1752
+ plugin(app, args);
1753
+ } else {
1754
+ plugin.install(app, args);
1755
+ }
1756
+ M._globle_plugin.add(plugin);
1757
+ plugin.installed = true;
1758
+ }else {
1759
+ if (Array.isArray(url)) {
1760
+ url.forEach(u=>{
1761
+ let regExp=new RegExp(u)
1762
+ G._use[u] = {url,regExp,callback};
1763
+ })
1764
+ } else {
1765
+ let regExp=new RegExp(url)
1766
+ G._use[url] = {url,regExp,callback};
1767
+ }
1768
+ }
1769
+ return app;
1770
+ }
1771
+
1772
+ app.installPlugin=async function (pluginUrl,constructorParams,pluginParams){
1773
+ if(M._globle_plugin_url_cacheMap[pluginUrl]){
1774
+ return
1775
+ }
1776
+ M._globle_plugin_url_cacheMap[pluginUrl]=pluginUrl;
1777
+ const Plugin= await M.require(pluginUrl);
1778
+ const plugin= new Plugin(constructorParams);
1779
+ app.use(plugin,pluginParams)
1780
+ }
1781
+
1782
+ /**
1783
+ * 注册get请求
1784
+ */
1785
+ app.get = function (url, callback) {
1786
+ url = M.formatUrl(url);
1787
+ var realUrl = url;
1788
+ if (url.indexOf(":") > 0) {
1789
+ url = url.substr(0, url.indexOf(":"));
1790
+ G._rest[url] = realUrl;
1791
+ }
1792
+
1793
+ G._get[url] = callback;
1794
+ }
1795
+ /**
1796
+ *注册post请求
1797
+ */
1798
+ app.post = function (url, callback) {
1799
+ url = M.formatUrl(url);
1800
+ var realUrl = url;
1801
+ if (url.indexOf(":") > 0) {
1802
+ url = url.substr(0, url.indexOf(":"));
1803
+ G._rest[url] = realUrl;
1804
+ }
1805
+ G._post[url] = callback;
1806
+ }
1807
+
1808
+ app.put = function (url, callback) {
1809
+ url = M.formatUrl(url);
1810
+ var realUrl = url;
1811
+ if (url.indexOf(":") > 0) {
1812
+ url = url.substr(0, url.indexOf(":"));
1813
+ G._rest[url] = realUrl;
1814
+ }
1815
+ G._put[url] = callback;
1816
+ }
1817
+
1818
+ app.delete = function (url, callback) {
1819
+ url = M.formatUrl(url);
1820
+ var realUrl = url;
1821
+ if (url.indexOf(":") > 0) {
1822
+ url = url.substr(0, url.indexOf(":"));
1823
+ G._rest[url] = realUrl;
1824
+ }
1825
+ G._delete[url] = callback;
1826
+ }
1827
+ /**
1828
+ *注册任意请求方法的请求
1829
+ */
1830
+ app.mapping = function (url, callback) {
1831
+ url = M.formatUrl(url);
1832
+ var realUrl = url;
1833
+ if (url.indexOf(":") > 0) {
1834
+ url = url.substr(0, url.indexOf(":"));
1835
+ G._rest[url] = realUrl;
1836
+ }
1837
+ G._mapping[url] = callback;
1838
+ }
1839
+
1840
+
1841
+ M.formatUrl = function (url) {
1842
+ if (!url.endsWith('/')) {
1843
+ url = url + '/';
1844
+ }
1845
+ if (!url.startsWith('/')) {
1846
+ url = '/' + url;
1847
+ }
1848
+ return url;
1849
+ }
1850
+ /**
1851
+ *转发
1852
+ */
1853
+ app.dispatch = function (url, req, res) {
1854
+ req.url = url;
1855
+ app(req, res);
1856
+ }
1857
+
1858
+ /**
1859
+ *重定向
1860
+ */
1861
+ app.redirect = function (url, req, res) {
1862
+ res.writeHead(302, {'Content-Type': 'text/html; charset=utf-8', 'Location': url});
1863
+ res.end();
1864
+ }
1865
+
1866
+ app.set = function (k, v) {
1867
+ M["_" + k] = v;
1868
+ }
1869
+
1870
+
1871
+ //全局异常钩子
1872
+ app.set("gloable_exception_handle",(err,req,res)=>{
1873
+ console.error(err.stack)
1874
+ if (res && !res.alreadySend) {
1858
1875
  // res.writeHead(500, { "Content-Type": "text/j;charset='utf-8'" });
1859
- res.send(M.result(err.message,false,-1));
1860
- }
1861
- })
1862
-
1863
- //render异常钩子
1864
- app.set("render_exception_handle",(err,req,res)=>{
1865
- console.error(err.stack)
1866
- })
1867
-
1868
- //没有对应接口时的处理器
1869
- app.set("no_router_handle",(req,res)=>{
1870
- res.end('no router')
1871
- })
1872
- //没有对应静态页的处理器
1873
- app.set("no_page_handle",(req,res)=>{
1874
- res.writeHead(404, { "Content-Type": "text/html;charset='utf-8'" });
1875
- res.write(`<!DOCTYPE html>
1876
+ res.send(M.result(err.message,false,-1));
1877
+ }
1878
+ })
1879
+
1880
+ //render异常钩子
1881
+ app.set("render_exception_handle",(err,req,res)=>{
1882
+ console.error(err.stack)
1883
+ })
1884
+
1885
+ //没有对应接口时的处理器
1886
+ app.set("no_router_handle",(req,res)=>{
1887
+ res.end('no router')
1888
+ })
1889
+ //没有对应静态页的处理器
1890
+ app.set("no_page_handle",(req,res)=>{
1891
+ res.writeHead(404, { "Content-Type": "text/html;charset='utf-8'" });
1892
+ res.write(`<!DOCTYPE html>
1876
1893
  <html lang="en">
1877
1894
  <head>
1878
1895
  <meta charset="UTF-8">
@@ -1889,102 +1906,102 @@ M.urlParse = function (url) {
1889
1906
  <p>no page</p>
1890
1907
  </body>
1891
1908
  </html>`
1892
- );
1893
- res.end();
1894
- })
1909
+ );
1910
+ res.end();
1911
+ })
1912
+
1913
+ app.listen = function (port) {
1914
+ const server= http.createServer(app).listen(port);
1915
+ console.log("listen on port:" + port);
1916
+ return server;
1917
+ }
1895
1918
 
1919
+ global.app=app;
1920
+ return app;
1921
+ }
1922
+ M["_gloable_exception_handle"]=(err)=>{
1923
+ console.error(err)
1924
+ }
1896
1925
 
1926
+ //异常捕获
1927
+ process.on('uncaughtException', function (err) {
1928
+ M["_gloable_exception_handle"](err,M.req,M.res);
1929
+ });
1930
+ //监听Promise没有被捕获的失败函数
1931
+ process.on('unhandledRejection',function(err,promise){
1932
+ M["_gloable_exception_handle"](err,M.req,M.res);
1933
+ });
1897
1934
 
1898
- app.listen = function (port) {
1899
- const server= http.createServer(app).listen(port);
1900
- console.log("listen on port:" + port);
1901
- return server;
1902
- }
1903
- return app;
1904
- }
1905
- M["_gloable_exception_handle"]=(err)=>{
1906
- console.error(err)
1907
- }
1908
-
1909
- //异常捕获
1910
- process.on('uncaughtException', function (err) {
1911
- M["_gloable_exception_handle"](err,M.req,M.res);
1912
- });
1913
- //监听Promise没有被捕获的失败函数
1914
- process.on('unhandledRejection',function(err,promise){
1915
- M["_gloable_exception_handle"](err,M.req,M.res);
1916
- });
1917
-
1918
-
1919
- /**
1920
- * 代理服务器start
1921
- */
1922
- M.getAxiosConfig = async (req) => {
1923
- return new Promise((resolve, reject) => {
1924
- let axiosConfig = {}
1925
- axiosConfig.url = M.proxyHost + req.url
1926
- axiosConfig.method = req.method.toLocaleLowerCase();
1927
- axiosConfig.headers = req.headers
1928
- let postStr = '';
1929
- req.on('data', function (chunk) {
1930
- postStr += chunk;
1931
- })
1932
- req.on('end', function (err, chunk) {
1933
- req.body = postStr; /*表示拿到post的值*/
1934
- postData = "";
1935
- try {
1936
- if (req.body.indexOf("=") == -1) {
1937
- postData = JSON.parse(req.body);
1938
- } else {
1939
- postData = url_module.parse("?" + req.body, true).query;
1940
- }
1941
- } catch (e) {
1942
- }
1943
- axiosConfig.data = postData;
1944
- axiosConfig.body = req.body;
1945
- resolve(axiosConfig)
1946
- })
1947
- })
1948
- }
1949
-
1950
- M.axios = function (axiosConfig) {
1951
- axiosConfig.headers.host = "";
1952
- var urlObj = url_module.parse(axiosConfig.url)
1953
- var options = {
1954
- hostname: urlObj.hostname,
1955
- port: urlObj.port,
1956
- path: urlObj.path,
1957
- method: axiosConfig.method.toLocaleUpperCase(),
1958
- headers: axiosConfig.headers
1959
- }
1960
- let reqHttp = http;
1961
- if (axiosConfig.url.startsWith("https")) {
1962
- reqHttp = https;
1963
- }
1964
- var html = '';
1965
- return new Promise((resolve, reject) => {
1966
- var req = reqHttp.request(options, function (res) {
1967
- options = M.httpBefore(options);
1968
- if (options == false) {
1969
- return;
1970
- }
1971
- res.setEncoding('utf-8');
1972
- res.on('data', function (chunk) {
1973
- html += chunk;
1974
- });
1975
- res.on('end', function () {
1976
- M.httpEnd(html);
1977
- resolve(html);
1978
- });
1979
-
1980
- });
1981
- req.on('error', function (err) {
1982
- console.error(err);
1983
- });
1984
- req.write(axiosConfig.body);
1985
- req.end();
1986
- })
1987
- }
1935
+
1936
+ /**
1937
+ * 代理服务器start
1938
+ */
1939
+ M.getAxiosConfig = async (req) => {
1940
+ return new Promise((resolve, reject) => {
1941
+ let axiosConfig = {}
1942
+ axiosConfig.url = M.proxyHost + req.url
1943
+ axiosConfig.method = req.method.toLocaleLowerCase();
1944
+ axiosConfig.headers = req.headers
1945
+ let postStr = '';
1946
+ req.on('data', function (chunk) {
1947
+ postStr += chunk;
1948
+ })
1949
+ req.on('end', function (err, chunk) {
1950
+ req.body = postStr; /*表示拿到post的值*/
1951
+ postData = "";
1952
+ try {
1953
+ if (req.body.indexOf("=") == -1) {
1954
+ postData = JSON.parse(req.body);
1955
+ } else {
1956
+ postData = url_module.parse("?" + req.body, true).query;
1957
+ }
1958
+ } catch (e) {
1959
+ }
1960
+ axiosConfig.data = postData;
1961
+ axiosConfig.body = req.body;
1962
+ resolve(axiosConfig)
1963
+ })
1964
+ })
1965
+ }
1966
+
1967
+ M.axios = function (axiosConfig) {
1968
+ axiosConfig.headers.host = "";
1969
+ var urlObj = url_module.parse(axiosConfig.url)
1970
+ var options = {
1971
+ hostname: urlObj.hostname,
1972
+ port: urlObj.port,
1973
+ path: urlObj.path,
1974
+ method: axiosConfig.method.toLocaleUpperCase(),
1975
+ headers: axiosConfig.headers
1976
+ }
1977
+ let reqHttp = http;
1978
+ if (axiosConfig.url.startsWith("https")) {
1979
+ reqHttp = https;
1980
+ }
1981
+ var html = '';
1982
+ return new Promise((resolve, reject) => {
1983
+ var req = reqHttp.request(options, function (res) {
1984
+ options = M.httpBefore(options);
1985
+ if (options == false) {
1986
+ return;
1987
+ }
1988
+ res.setEncoding('utf-8');
1989
+ res.on('data', function (chunk) {
1990
+ html += chunk;
1991
+ });
1992
+ res.on('end', function () {
1993
+ M.httpEnd(html);
1994
+ resolve(html);
1995
+ });
1996
+
1997
+ });
1998
+ req.on('error', function (err) {
1999
+ console.error(err);
2000
+ });
2001
+ req.write(axiosConfig.body);
2002
+ req.end();
2003
+ })
2004
+ }
1988
2005
  /**
1989
2006
  * 代理服务器end
1990
2007
  */
@@ -1995,213 +2012,213 @@ M.urlParse = function (url) {
1995
2012
  privateObj.dealUseServer = async function (req, res) {
1996
2013
  for (let key in M._use){
1997
2014
  if(M._use[key].regExp.test(req.url)){
1998
- await M._use[key].callback(req,res);
1999
- return;
2015
+ await M._use[key].callback(req,res);
2016
+ return;
2000
2017
  }
2001
2018
  }
2002
2019
  }
2003
2020
 
2004
- privateObj.staticServer = async function (req, res, staticPath) {
2005
- if (res.alreadySend) return;
2006
- var pathname = url_module.parse(req.url).pathname; /*获取url的值*/
2007
- if (pathname == '/') {
2008
- pathname = '/index.html'; /*默认加载的首页*/
2009
- }
2010
- let fileName = pathname.replace("/", "");
2011
- //获取文件的后缀名
2012
- var extname = path.extname(pathname);
2013
-
2014
- if (fileName.startsWith("__default_")) {
2015
- res.setHeader("Access-Control-Allow-Origin", "*");
2016
- res.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
2017
- res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
2018
- res.setHeader("X-Powered-By", ' 3.2.1')
2019
- res.writeHead(200, {"Content-Type": "" + (privateObj.staticMime[extname] || 'text/html') + ";charset='utf-8'",});
2020
- res.write(M.__default_file[fileName]);
2021
- res.end(); /*结束响应*/
2022
- return;
2023
- }
2024
- if (M.remoteStaticPathEnable && req.url.endsWith("remote=true")) {
2025
- if (!res.alreadySend) await res.renderUrl(M.remoteStaticPath + pathname)
2026
- return;
2027
- }
2028
-
2029
- if (pathname != '/favicon.ico') { /*过滤请求favicon.ico*/
2030
- //文件操作获取 static下面的index.html
2031
- fs.readFile(staticPath + '/' + pathname, function (err, data) {
2032
- if (err) { /*么有这个文件*/
2033
- M["_no_page_handle"](req,res);
2034
- } else { /*返回这个文件*/
2035
- res.setHeader("Access-Control-Allow-Origin", "*");
2036
- res.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
2037
- res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
2038
- res.setHeader("X-Powered-By", ' 3.2.1')
2039
- res.writeHead(200, {"Content-Type": "" + (privateObj.staticMime[extname] || 'text/html') + ";charset='utf-8'",});
2040
- res.write(data);
2041
- res.end(); /*结束响应*/
2042
- }
2043
- })
2044
- } else {
2045
- res.writeHead(302, {
2046
- 'Content-Type': 'image/x-icon; charset=utf-8',
2047
- 'Location': "https://q.qlogo.cn/g?b=qq&nk=934031452&s=100"
2048
- });
2049
- res.end();
2050
- }
2051
- }
2052
-
2053
- /*SSE SERVER */
2054
- M.sseServer = function () {
2021
+ privateObj.staticServer = async function (req, res, staticPath) {
2022
+ if (res.alreadySend) return;
2023
+ var pathname = url_module.parse(req.url).pathname; /*获取url的值*/
2024
+ if (pathname == '/') {
2025
+ pathname = '/index.html'; /*默认加载的首页*/
2026
+ }
2027
+ let fileName = pathname.replace("/", "");
2028
+ //获取文件的后缀名
2029
+ var extname = path.extname(pathname);
2030
+
2031
+ if (fileName.startsWith("__default_")) {
2032
+ res.setHeader("Access-Control-Allow-Origin", "*");
2033
+ res.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
2034
+ res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
2035
+ res.setHeader("X-Powered-By", ' 3.2.1')
2036
+ res.writeHead(200, {"Content-Type": "" + (privateObj.staticMime[extname] || 'text/html') + ";charset='utf-8'",});
2037
+ res.write(M.__default_file[fileName]);
2038
+ res.end(); /*结束响应*/
2039
+ return;
2040
+ }
2041
+ if (M.remoteStaticPathEnable && req.url.endsWith("remote=true")) {
2042
+ if (!res.alreadySend) await res.renderUrl(M.remoteStaticPath + pathname)
2043
+ return;
2044
+ }
2045
+
2046
+ if (pathname != '/favicon.ico') { /*过滤请求favicon.ico*/
2047
+ //文件操作获取 static下面的index.html
2048
+ fs.readFile(staticPath + '/' + pathname, function (err, data) {
2049
+ if (err) { /*么有这个文件*/
2050
+ M["_no_page_handle"](req,res);
2051
+ } else { /*返回这个文件*/
2052
+ res.setHeader("Access-Control-Allow-Origin", "*");
2053
+ res.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
2054
+ res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
2055
+ res.setHeader("X-Powered-By", ' 3.2.1')
2056
+ res.writeHead(200, {"Content-Type": "" + (privateObj.staticMime[extname] || 'text/html') + ";charset='utf-8'",});
2057
+ res.write(data);
2058
+ res.end(); /*结束响应*/
2059
+ }
2060
+ })
2061
+ } else {
2062
+ res.writeHead(302, {
2063
+ 'Content-Type': 'image/x-icon; charset=utf-8',
2064
+ 'Location': "https://q.qlogo.cn/g?b=qq&nk=934031452&s=100"
2065
+ });
2066
+ res.end();
2067
+ }
2068
+ }
2069
+
2070
+ /*SSE SERVER */
2071
+ M.sseServer = function () {
2055
2072
  //sse 心跳
2056
- function headBeat(){
2057
- try {
2058
- let clientIdList= Array.from(M._sseClientMap.keys());
2059
- for (let i=0;i<clientIdList.length;i++){
2060
- let clientId= clientIdList[i];
2061
- let res= M._sseClientMap.get(clientId).res;
2062
- let r= res.write(': \n\n');
2063
- if(!r){
2064
- M._sseClientMap.delete(clientId);
2065
- M["_sse_disconnect"](clientId);
2066
- }
2067
- }
2068
- }catch (e){
2073
+ function headBeat(){
2074
+ try {
2075
+ let clientIdList= Array.from(M._sseClientMap.keys());
2076
+ for (let i=0;i<clientIdList.length;i++){
2077
+ let clientId= clientIdList[i];
2078
+ let res= M._sseClientMap.get(clientId).res;
2079
+ let r= res.write(': \n\n');
2080
+ if(!r){
2081
+ M._sseClientMap.delete(clientId);
2082
+ M["_sse_disconnect"](clientId);
2083
+ }
2084
+ }
2085
+ }catch (e){
2069
2086
  console.error(e);
2070
- }
2071
- }
2087
+ }
2088
+ }
2072
2089
 
2073
- M["_sse_connection"]=(clientId)=>{
2074
- console.log(clientId+" connection")
2075
- }
2090
+ M["_sse_connection"]=(clientId)=>{
2091
+ console.log(clientId+" connection")
2092
+ }
2076
2093
 
2077
- M["_sse_disconnect"]=(clientId)=>{
2078
- console.log(clientId+" disconnect")
2079
- }
2094
+ M["_sse_disconnect"]=(clientId)=>{
2095
+ console.log(clientId+" disconnect")
2096
+ }
2080
2097
 
2081
- M["_sse_send"]=(clientId,msg)=>{
2098
+ M["_sse_send"]=(clientId,msg)=>{
2082
2099
  // console.log("sse_send",clientId,msg)
2083
- }
2084
-
2085
- event.on('sseSendMsg', function (sendData,clientId,eventName="slide",id=+new Date()) {
2086
- let sendObj={event:eventName,id:id,data:JSON.stringify(sendData),retry:10000}
2087
- if(!clientId){
2088
- let clientIdList= Array.from(M._sseClientMap.keys())
2089
- for (let i=0;i<clientIdList.length;i++){
2090
- let clientId= clientIdList[i];
2091
- let res=M._sseClientMap.get(clientId)?M._sseClientMap.get(clientId).res:null;
2092
- if(res==null){
2093
- continue;
2094
- }
2095
- res.write(`event: ${sendObj.event}\n`); // 事件类型
2096
- res.write(`id: ${sendObj.id}\n`); // 消息 ID
2097
- res.write(`data: ${sendObj.data}\n`); // 消息数据
2098
- res.write(`retry: ${sendObj.retry}\n`); // 重连时间
2099
- res.write('\n\n'); // 消息结束
2100
- }
2101
- }else {
2102
- let res=M._sseClientMap.get(clientId)?M._sseClientMap.get(clientId).res:null;
2103
- if(res==null){
2104
- return
2105
- }
2106
- res.write(`event: ${sendObj.event}\n`); // 事件类型
2107
- res.write(`id: ${sendObj.id}\n`); // 消息 ID
2108
- res.write(`data: ${sendObj.data}\n`); // 消息数据
2109
- res.write(`retry: ${sendObj.retry}\n`); // 重连时间
2110
- res.write('\n\n'); // 消息结束
2111
- }
2112
- M["_sse_send"](clientId,sendObj);
2113
- })
2114
- setInterval(() => {
2115
- headBeat();
2116
- }, M._sseHeatTime);
2117
-
2118
- let app = function (req, res) {
2119
- headBeat();
2120
- let clientId=req.params.clientId;
2121
- let connectionRes= M["_sse_connection"](clientId);
2122
- if(connectionRes==false){
2123
- return;
2124
- }
2125
- M._sseClientMap.set(clientId,{res});
2126
- res.writeHead(200, {
2127
- 'Content-Type': 'text/event-stream',
2128
- 'Cache-Control': 'no-cache',
2129
- 'Connection': 'keep-alive',
2130
- 'Access-Control-Allow-Origin': '*',
2131
- });
2132
- };
2133
- app.send = function (msg,clientId,eventName,id) {
2134
- event.emit('sseSendMsg', msg,clientId,eventName,id);
2135
- }
2136
-
2137
- app.call = function (eventName,msg,clientId,id) {
2138
- event.emit('sseSendMsg', msg,clientId,eventName,id);
2139
- }
2140
-
2141
- app.set = function (k, v) {
2142
- M["_" + k] = v;
2143
- }
2144
-
2145
- app.listen = function (port) {
2146
- let serverObj = http.createServer(app).listen(port);
2147
- app.serverObj = serverObj;
2148
- console.log("SSE Server listen on port:" + port);
2149
- return app;
2150
- }
2151
- return app;
2152
- }
2153
-
2154
- /**
2155
- * ----------------------服务器端END--------------------------------------------
2156
- */
2157
-
2158
-
2159
- /**
2160
- * ----------------------其他工具函数START--------------------------------------------
2161
- */
2162
- M.exec = function (comand) {
2163
- var promise = new Promise(function (reslove, reject) {
2164
- child_process.exec(comand, function (err, stdout, stderr) {
2165
- if (err || stderr) console.error(err, stderr);
2166
- reslove(stdout);
2167
- });
2168
-
2169
- })
2170
- return promise;
2171
- }
2172
-
2173
- M.getMyIp = function () {
2174
- var interfaces = require('os').networkInterfaces();
2175
- for (var devName in interfaces) {
2176
- var iface = interfaces[devName];
2177
- for (var i = 0; i < iface.length; i++) {
2178
- var alias = iface[i];
2179
- if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
2180
- return alias.address;
2181
- }
2182
- }
2183
- }
2184
- }
2185
-
2186
- /**
2187
- *对象转JSON key不用引号括起来,因兼容性不好,所以去掉
2188
- */
2189
-
2190
- /**
2191
- M.JSOM_Stringify=function(obj){
2100
+ }
2101
+
2102
+ event.on('sseSendMsg', function (sendData,clientId,eventName="slide",id=+new Date()) {
2103
+ let sendObj={event:eventName,id:id,data:JSON.stringify(sendData),retry:10000}
2104
+ if(!clientId){
2105
+ let clientIdList= Array.from(M._sseClientMap.keys())
2106
+ for (let i=0;i<clientIdList.length;i++){
2107
+ let clientId= clientIdList[i];
2108
+ let res=M._sseClientMap.get(clientId)?M._sseClientMap.get(clientId).res:null;
2109
+ if(res==null){
2110
+ continue;
2111
+ }
2112
+ res.write(`event: ${sendObj.event}\n`); // 事件类型
2113
+ res.write(`id: ${sendObj.id}\n`); // 消息 ID
2114
+ res.write(`data: ${sendObj.data}\n`); // 消息数据
2115
+ res.write(`retry: ${sendObj.retry}\n`); // 重连时间
2116
+ res.write('\n\n'); // 消息结束
2117
+ }
2118
+ }else {
2119
+ let res=M._sseClientMap.get(clientId)?M._sseClientMap.get(clientId).res:null;
2120
+ if(res==null){
2121
+ return
2122
+ }
2123
+ res.write(`event: ${sendObj.event}\n`); // 事件类型
2124
+ res.write(`id: ${sendObj.id}\n`); // 消息 ID
2125
+ res.write(`data: ${sendObj.data}\n`); // 消息数据
2126
+ res.write(`retry: ${sendObj.retry}\n`); // 重连时间
2127
+ res.write('\n\n'); // 消息结束
2128
+ }
2129
+ M["_sse_send"](clientId,sendObj);
2130
+ })
2131
+ setInterval(() => {
2132
+ headBeat();
2133
+ }, M._sseHeatTime);
2134
+
2135
+ let app = function (req, res) {
2136
+ headBeat();
2137
+ let clientId=req.params.clientId;
2138
+ let connectionRes= M["_sse_connection"](clientId);
2139
+ if(connectionRes==false){
2140
+ return;
2141
+ }
2142
+ M._sseClientMap.set(clientId,{res});
2143
+ res.writeHead(200, {
2144
+ 'Content-Type': 'text/event-stream',
2145
+ 'Cache-Control': 'no-cache',
2146
+ 'Connection': 'keep-alive',
2147
+ 'Access-Control-Allow-Origin': '*',
2148
+ });
2149
+ };
2150
+ app.send = function (msg,clientId,eventName,id) {
2151
+ event.emit('sseSendMsg', msg,clientId,eventName,id);
2152
+ }
2153
+
2154
+ app.call = function (eventName,msg,clientId,id) {
2155
+ event.emit('sseSendMsg', msg,clientId,eventName,id);
2156
+ }
2157
+
2158
+ app.set = function (k, v) {
2159
+ M["_" + k] = v;
2160
+ }
2161
+
2162
+ app.listen = function (port) {
2163
+ let serverObj = http.createServer(app).listen(port);
2164
+ app.serverObj = serverObj;
2165
+ console.log("SSE Server listen on port:" + port);
2166
+ return app;
2167
+ }
2168
+ return app;
2169
+ }
2170
+
2171
+ /**
2172
+ * ----------------------服务器端END--------------------------------------------
2173
+ */
2174
+
2175
+
2176
+ /**
2177
+ * ----------------------其他工具函数START--------------------------------------------
2178
+ */
2179
+ M.exec = function (comand) {
2180
+ var promise = new Promise(function (reslove, reject) {
2181
+ child_process.exec(comand, function (err, stdout, stderr) {
2182
+ if (err || stderr) console.error(err, stderr);
2183
+ reslove(stdout);
2184
+ });
2185
+
2186
+ })
2187
+ return promise;
2188
+ }
2189
+
2190
+ M.getMyIp = function () {
2191
+ var interfaces = require('os').networkInterfaces();
2192
+ for (var devName in interfaces) {
2193
+ var iface = interfaces[devName];
2194
+ for (var i = 0; i < iface.length; i++) {
2195
+ var alias = iface[i];
2196
+ if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
2197
+ return alias.address;
2198
+ }
2199
+ }
2200
+ }
2201
+ }
2202
+
2203
+ /**
2204
+ *对象转JSON key不用引号括起来,因兼容性不好,所以去掉
2205
+ */
2206
+
2207
+ /**
2208
+ M.JSOM_Stringify=function(obj){
2192
2209
  return JSON.stringify(obj).replace(/"(\w+)"(\s*:\s*)/gis, '$1$2');
2193
2210
  }
2194
- */
2195
-
2196
- M.sleep = function (numberMillis) {
2197
- var now = new Date();
2198
- var exitTime = now.getTime() + numberMillis;
2199
- while (true) {
2200
- now = new Date();
2201
- if (now.getTime() > exitTime)
2202
- return;
2203
- }
2204
- }
2211
+ */
2212
+
2213
+ M.sleep = function (numberMillis) {
2214
+ var now = new Date();
2215
+ var exitTime = now.getTime() + numberMillis;
2216
+ while (true) {
2217
+ now = new Date();
2218
+ if (now.getTime() > exitTime)
2219
+ return;
2220
+ }
2221
+ }
2205
2222
 
2206
2223
  M.delayMs=async function (ms){
2207
2224
  return new Promise(r=>{
@@ -2211,604 +2228,607 @@ M.delayMs=async function (ms){
2211
2228
  })
2212
2229
  }
2213
2230
 
2214
- /**
2215
- * ----------------------其他工具函数END--------------------------------------------
2216
- */
2217
-
2218
- /**
2219
- * 静态资源对应表
2220
- */
2221
- privateObj.staticMime = {
2222
- ".323": "text/h323",
2223
- ".3gp": "video/3gpp",
2224
- ".aab": "application/x-authoware-bin",
2225
- ".aam": "application/x-authoware-map",
2226
- ".aas": "application/x-authoware-seg",
2227
- ".acx": "application/internet-property-stream",
2228
- ".ai": "application/postscript",
2229
- ".aif": "audio/x-aiff",
2230
- ".aifc": "audio/x-aiff",
2231
- ".aiff": "audio/x-aiff",
2232
- ".als": "audio/X-Alpha5",
2233
- ".amc": "application/x-mpeg",
2234
- ".ani": "application/octet-stream",
2235
- ".apk": "application/vnd.android.package-archive",
2236
- ".asc": "text/plain",
2237
- ".asd": "application/astound",
2238
- ".asf": "video/x-ms-asf",
2239
- ".asn": "application/astound",
2240
- ".asp": "application/x-asap",
2241
- ".asr": "video/x-ms-asf",
2242
- ".asx": "video/x-ms-asf",
2243
- ".au": "audio/basic",
2244
- ".avb": "application/octet-stream",
2245
- ".avi": "video/x-msvideo",
2246
- ".awb": "audio/amr-wb",
2247
- ".axs": "application/olescript",
2248
- ".bas": "text/plain",
2249
- ".bcpio": "application/x-bcpio",
2250
- ".bin ": "application/octet-stream",
2251
- ".bld": "application/bld",
2252
- ".bld2": "application/bld2",
2253
- ".bmp": "image/bmp",
2254
- ".bpk": "application/octet-stream",
2255
- ".bz2": "application/x-bzip2",
2256
- ".c": "text/plain",
2257
- ".cal": "image/x-cals",
2258
- ".cat": "application/vnd.ms-pkiseccat",
2259
- ".ccn": "application/x-cnc",
2260
- ".cco": "application/x-cocoa",
2261
- ".cdf": "application/x-cdf",
2262
- ".cer": "application/x-x509-ca-cert",
2263
- ".cgi": "magnus-internal/cgi",
2264
- ".chat": "application/x-chat",
2265
- ".class": "application/octet-stream",
2266
- ".clp": "application/x-msclip",
2267
- ".cmx": "image/x-cmx",
2268
- ".co": "application/x-cult3d-object",
2269
- ".cod": "image/cis-cod",
2270
- ".conf": "text/plain",
2271
- ".cpio": "application/x-cpio",
2272
- ".cpp": "text/plain",
2273
- ".cpt": "application/mac-compactpro",
2274
- ".crd": "application/x-mscardfile",
2275
- ".crl": "application/pkix-crl",
2276
- ".crt": "application/x-x509-ca-cert",
2277
- ".csh": "application/x-csh",
2278
- ".csm": "chemical/x-csml",
2279
- ".csml": "chemical/x-csml",
2280
- ".css": "text/css",
2281
- ".cur": "application/octet-stream",
2282
- ".dcm": "x-lml/x-evm",
2283
- ".dcr": "application/x-director",
2284
- ".dcx": "image/x-dcx",
2285
- ".der": "application/x-x509-ca-cert",
2286
- ".dhtml": "text/html",
2287
- ".dir": "application/x-director",
2288
- ".dll": "application/x-msdownload",
2289
- ".dmg": "application/octet-stream",
2290
- ".dms": "application/octet-stream",
2291
- ".doc": "application/msword",
2292
- ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
2293
- ".dot": "application/msword",
2294
- ".dvi": "application/x-dvi",
2295
- ".dwf": "drawing/x-dwf",
2296
- ".dwg": "application/x-autocad",
2297
- ".dxf": "application/x-autocad",
2298
- ".dxr": "application/x-director",
2299
- ".ebk": "application/x-expandedbook",
2300
- ".emb": "chemical/x-embl-dl-nucleotide",
2301
- ".embl": "chemical/x-embl-dl-nucleotide",
2302
- ".eps": "application/postscript",
2303
- ".epub": "application/epub+zip",
2304
- ".eri": "image/x-eri",
2305
- ".es": "audio/echospeech",
2306
- ".esl": "audio/echospeech",
2307
- ".etc": "application/x-earthtime",
2308
- ".etx": "text/x-setext",
2309
- ".evm": "x-lml/x-evm",
2310
- ".evy": "application/envoy",
2311
- ".exe": "application/octet-stream",
2312
- ".fh4": "image/x-freehand",
2313
- ".fh5": "image/x-freehand",
2314
- ".fhc": "image/x-freehand",
2315
- ".fif": "application/fractals",
2316
- ".flr": "x-world/x-vrml",
2317
- ".flv": "flv-application/octet-stream",
2318
- ".fm": "application/x-maker",
2319
- ".fpx": "image/x-fpx",
2320
- ".fvi": "video/isivideo",
2321
- ".gau": "chemical/x-gaussian-input",
2322
- ".gca": "application/x-gca-compressed",
2323
- ".gdb": "x-lml/x-gdb",
2324
- ".gif": "image/gif",
2325
- ".gps": "application/x-gps",
2326
- ".gtar": "application/x-gtar",
2327
- ".gz": "application/x-gzip",
2328
- ".h": "text/plain",
2329
- ".hdf": "application/x-hdf",
2330
- ".hdm": "text/x-hdml",
2331
- ".hdml": "text/x-hdml",
2332
- ".hlp": "application/winhlp",
2333
- ".hqx": "application/mac-binhex40",
2334
- ".hta": "application/hta",
2335
- ".htc": "text/x-component",
2336
- ".htm": "text/html",
2337
- ".html": "text/html",
2338
- ".hts": "text/html",
2339
- ".htt": "text/webviewhtml",
2340
- ".ice": "x-conference/x-cooltalk",
2341
- ".ico": "image/x-icon",
2342
- ".ief": "image/ief",
2343
- ".ifm": "image/gif",
2344
- ".ifs": "image/ifs",
2345
- ".iii": "application/x-iphone",
2346
- ".imy": "audio/melody",
2347
- ".ins": "application/x-internet-signup",
2348
- ".ips": "application/x-ipscript",
2349
- ".ipx": "application/x-ipix",
2350
- ".isp": "application/x-internet-signup",
2351
- ".it": "audio/x-mod",
2352
- ".itz": "audio/x-mod",
2353
- ".ivr": "i-world/i-vrml",
2354
- ".j2k": "image/j2k",
2355
- ".jad": "text/vnd.sun.j2me.app-descriptor",
2356
- ".jam": "application/x-jam",
2357
- ".jar": "application/java-archive",
2358
- ".java": "text/plain",
2359
- ".jfif": "image/pipeg",
2360
- ".jnlp": "application/x-java-jnlp-file",
2361
- ".jpe": "image/jpeg",
2362
- ".jpeg": "image/jpeg",
2363
- ".jpg": "image/jpeg",
2364
- ".jpz": "image/jpeg",
2365
- ".js": "application/javascript",
2366
- ".jsx": "application/javascript",
2367
- ".woff":" application/x-font-woff",
2368
- ".woff2":" application/x-font-woff",
2369
- ".jwc": "application/jwc",
2370
- ".kjx": "application/x-kjx",
2371
- ".lak": "x-lml/x-lak",
2372
- ".latex": "application/x-latex",
2373
- ".lcc": "application/fastman",
2374
- ".lcl": "application/x-digitalloca",
2375
- ".lcr": "application/x-digitalloca",
2376
- ".lgh": "application/lgh",
2377
- ".lha": "application/octet-stream",
2378
- ".lml": "x-lml/x-lml",
2379
- ".lmlpack": "x-lml/x-lmlpack",
2380
- ".log": "text/plain",
2381
- ".lsf": "video/x-la-asf",
2382
- ".lsx": "video/x-la-asf",
2383
- ".lzh": "application/octet-stream",
2384
- ".m13": "application/x-msmediaview",
2385
- ".m14": "application/x-msmediaview",
2386
- ".m15": "audio/x-mod",
2387
- ".m3u": "audio/x-mpegurl",
2388
- ".m3url": "audio/x-mpegurl",
2389
- ".m4a": "audio/mp4a-latm",
2390
- ".m4b": "audio/mp4a-latm",
2391
- ".m4p": "audio/mp4a-latm",
2392
- ".m4u": "video/vnd.mpegurl",
2393
- ".m4v": "video/x-m4v",
2394
- ".ma1": "audio/ma1",
2395
- ".ma2": "audio/ma2",
2396
- ".ma3": "audio/ma3",
2397
- ".ma5": "audio/ma5",
2398
- ".man": "application/x-troff-man",
2399
- ".map": "magnus-internal/imagemap",
2400
- ".mbd": "application/mbedlet",
2401
- ".mct": "application/x-mascot",
2402
- ".mdb": "application/x-msaccess",
2403
- ".mdz": "audio/x-mod",
2404
- ".me": "application/x-troff-me",
2405
- ".mel": "text/x-vmel",
2406
- ".mht": "message/rfc822",
2407
- ".mhtml": "message/rfc822",
2408
- ".mi": "application/x-mif",
2409
- ".mid": "audio/mid",
2410
- ".midi": "audio/midi",
2411
- ".mif": "application/x-mif",
2412
- ".mil": "image/x-cals",
2413
- ".mio": "audio/x-mio",
2414
- ".mmf": "application/x-skt-lbs",
2415
- ".mng": "video/x-mng",
2416
- ".mny": "application/x-msmoney",
2417
- ".moc": "application/x-mocha",
2418
- ".mocha": "application/x-mocha",
2419
- ".mod": "audio/x-mod",
2420
- ".mof": "application/x-yumekara",
2421
- ".mol": "chemical/x-mdl-molfile",
2422
- ".mop": "chemical/x-mopac-input",
2423
- ".mov": "video/quicktime",
2424
- ".movie": "video/x-sgi-movie",
2425
- ".mp2": "video/mpeg",
2426
- ".mp3": "audio/mpeg",
2427
- ".mp4": "video/mp4",
2428
- ".mpa": "video/mpeg",
2429
- ".mpc": "application/vnd.mpohun.certificate",
2430
- ".mpe": "video/mpeg",
2431
- ".mpeg": "video/mpeg",
2432
- ".mpg": "video/mpeg",
2433
- ".mpg4": "video/mp4",
2434
- ".mpga": "audio/mpeg",
2435
- ".mpn": "application/vnd.mophun.application",
2436
- ".mpp": "application/vnd.ms-project",
2437
- ".mps": "application/x-mapserver",
2438
- ".mpv2": "video/mpeg",
2439
- ".mrl": "text/x-mrml",
2440
- ".mrm": "application/x-mrm",
2441
- ".ms": "application/x-troff-ms",
2442
- ".msg": "application/vnd.ms-outlook",
2443
- ".mts": "application/metastream",
2444
- ".mtx": "application/metastream",
2445
- ".mtz": "application/metastream",
2446
- ".mvb": "application/x-msmediaview",
2447
- ".mzv": "application/metastream",
2448
- ".nar": "application/zip",
2449
- ".nbmp": "image/nbmp",
2450
- ".nc": "application/x-netcdf",
2451
- ".ndb": "x-lml/x-ndb",
2452
- ".ndwn": "application/ndwn",
2453
- ".nif": "application/x-nif",
2454
- ".nmz": "application/x-scream",
2455
- ".nokia-op-logo": "image/vnd.nok-oplogo-color",
2456
- ".npx": "application/x-netfpx",
2457
- ".nsnd": "audio/nsnd",
2458
- ".nva": "application/x-neva1",
2459
- ".nws": "message/rfc822",
2460
- ".oda": "application/oda",
2461
- ".ogg": "audio/ogg",
2462
- ".oom": "application/x-AtlasMate-Plugin",
2463
- ".p10": "application/pkcs10",
2464
- ".p12": "application/x-pkcs12",
2465
- ".p7b": "application/x-pkcs7-certificates",
2466
- ".p7c": "application/x-pkcs7-mime",
2467
- ".p7m": "application/x-pkcs7-mime",
2468
- ".p7r": "application/x-pkcs7-certreqresp",
2469
- ".p7s": "application/x-pkcs7-signature",
2470
- ".pac": "audio/x-pac",
2471
- ".pae": "audio/x-epac",
2472
- ".pan": "application/x-pan",
2473
- ".pbm": "image/x-portable-bitmap",
2474
- ".pcx": "image/x-pcx",
2475
- ".pda": "image/x-pda",
2476
- ".pdb": "chemical/x-pdb",
2477
- ".pdf": "application/pdf",
2478
- ".pfr": "application/font-tdpfr",
2479
- ".pfx": "application/x-pkcs12",
2480
- ".pgm": "image/x-portable-graymap",
2481
- ".pict": "image/x-pict",
2482
- ".pko": "application/ynd.ms-pkipko",
2483
- ".pm": "application/x-perl",
2484
- ".pma": "application/x-perfmon",
2485
- ".pmc": "application/x-perfmon",
2486
- ".pmd": "application/x-pmd",
2487
- ".pml": "application/x-perfmon",
2488
- ".pmr": "application/x-perfmon",
2489
- ".pmw": "application/x-perfmon",
2490
- ".png": "image/png",
2491
- ".pnm": "image/x-portable-anymap",
2492
- ".pnz": "image/png",
2493
- ".pot,": "application/vnd.ms-powerpoint",
2494
- ".ppm": "image/x-portable-pixmap",
2495
- ".pps": "application/vnd.ms-powerpoint",
2496
- ".ppt": "application/vnd.ms-powerpoint",
2497
- ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
2498
- ".pqf": "application/x-cprplayer",
2499
- ".pqi": "application/cprplayer",
2500
- ".prc": "application/x-prc",
2501
- ".prf": "application/pics-rules",
2502
- ".prop": "text/plain",
2503
- ".proxy": "application/x-ns-proxy-autoconfig",
2504
- ".ps": "application/postscript",
2505
- ".ptlk": "application/listenup",
2506
- ".pub": "application/x-mspublisher",
2507
- ".pvx": "video/x-pv-pvx",
2508
- ".qcp": "audio/vnd.qcelp",
2509
- ".qt": "video/quicktime",
2510
- ".qti": "image/x-quicktime",
2511
- ".qtif": "image/x-quicktime",
2512
- ".r3t": "text/vnd.rn-realtext3d",
2513
- ".ra": "audio/x-pn-realaudio",
2514
- ".ram": "audio/x-pn-realaudio",
2515
- ".rar": "application/octet-stream",
2516
- ".ras": "image/x-cmu-raster",
2517
- ".rc": "text/plain",
2518
- ".rdf": "application/rdf+xml",
2519
- ".rf": "image/vnd.rn-realflash",
2520
- ".rgb": "image/x-rgb",
2521
- ".rlf": "application/x-richlink",
2522
- ".rm": "audio/x-pn-realaudio",
2523
- ".rmf": "audio/x-rmf",
2524
- ".rmi": "audio/mid",
2525
- ".rmm": "audio/x-pn-realaudio",
2526
- ".rmvb": "audio/x-pn-realaudio",
2527
- ".rnx": "application/vnd.rn-realplayer",
2528
- ".roff": "application/x-troff",
2529
- ".rp": "image/vnd.rn-realpix",
2530
- ".rpm": "audio/x-pn-realaudio-plugin",
2531
- ".rt": "text/vnd.rn-realtext",
2532
- ".rte": "x-lml/x-gps",
2533
- ".rtf": "application/rtf",
2534
- ".rtg": "application/metastream",
2535
- ".rtx": "text/richtext",
2536
- ".rv": "video/vnd.rn-realvideo",
2537
- ".rwc": "application/x-rogerwilco",
2538
- ".s3m": "audio/x-mod",
2539
- ".s3z": "audio/x-mod",
2540
- ".sca": "application/x-supercard",
2541
- ".scd": "application/x-msschedule",
2542
- ".sct": "text/scriptlet",
2543
- ".sdf": "application/e-score",
2544
- ".sea": "application/x-stuffit",
2545
- ".setpay": "application/set-payment-initiation",
2546
- ".setreg": "application/set-registration-initiation",
2547
- ".sgm": "text/x-sgml",
2548
- ".sgml": "text/x-sgml",
2549
- ".sh": "application/x-sh",
2550
- ".shar": "application/x-shar",
2551
- ".shtml": "magnus-internal/parsed-html",
2552
- ".shw": "application/presentations",
2553
- ".si6": "image/si6",
2554
- ".si7": "image/vnd.stiwap.sis",
2555
- ".si9": "image/vnd.lgtwap.sis",
2556
- ".sis": "application/vnd.symbian.install",
2557
- ".sit": "application/x-stuffit",
2558
- ".skd": "application/x-Koan",
2559
- ".skm": "application/x-Koan",
2560
- ".skp": "application/x-Koan",
2561
- ".skt": "application/x-Koan",
2562
- ".slc": "application/x-salsa",
2563
- ".smd": "audio/x-smd",
2564
- ".smi": "application/smil",
2565
- ".smil": "application/smil",
2566
- ".smp": "application/studiom",
2567
- ".smz": "audio/x-smd",
2568
- ".snd": "audio/basic",
2569
- ".spc": "application/x-pkcs7-certificates",
2570
- ".spl": "application/futuresplash",
2571
- ".spr": "application/x-sprite",
2572
- ".sprite": "application/x-sprite",
2573
- ".sdp": "application/sdp",
2574
- ".spt": "application/x-spt",
2575
- ".src": "application/x-wais-source",
2576
- ".sst": "application/vnd.ms-pkicertstore",
2577
- ".stk": "application/hyperstudio",
2578
- ".stl": "application/vnd.ms-pkistl",
2579
- ".stm": "text/html",
2580
- ".svg": "image/svg+xml",
2581
- ".sv4cpio": "application/x-sv4cpio",
2582
- ".sv4crc": "application/x-sv4crc",
2583
- ".svf": "image/vnd",
2584
- ".svh": "image/svh",
2585
- ".svr": "x-world/x-svr",
2586
- ".swf": "application/x-shockwave-flash",
2587
- ".swfl": "application/x-shockwave-flash",
2588
- ".t": "application/x-troff",
2589
- ".tad": "application/octet-stream",
2590
- ".talk": "text/x-speech",
2591
- ".tar": "application/x-tar",
2592
- ".taz": "application/x-tar",
2593
- ".tbp": "application/x-timbuktu",
2594
- ".tbt": "application/x-timbuktu",
2595
- ".tcl": "application/x-tcl",
2596
- ".tex": "application/x-tex",
2597
- ".texi": "application/x-texinfo",
2598
- ".texinfo": "application/x-texinfo",
2599
- ".tgz": "application/x-compressed",
2600
- ".thm": "application/vnd.eri.thm",
2601
- ".tif": "image/tiff",
2602
- ".tiff": "image/tiff",
2603
- ".tki": "application/x-tkined",
2604
- ".tkined": "application/x-tkined",
2605
- ".toc": "application/toc",
2606
- ".toy": "image/toy",
2607
- ".tr": "application/x-troff",
2608
- ".trk": "x-lml/x-gps",
2609
- ".trm": "application/x-msterminal",
2610
- ".tsi": "audio/tsplayer",
2611
- ".tsp": "application/dsptype",
2612
- ".tsv": "text/tab-separated-values",
2613
- ".ttf": "application/octet-stream",
2614
- ".ttz": "application/t-time",
2615
- ".txt": "text/plain",
2616
- ".uls": "text/iuls",
2617
- ".ult": "audio/x-mod",
2618
- ".ustar": "application/x-ustar",
2619
- ".uu": "application/x-uuencode",
2620
- ".uue": "application/x-uuencode",
2621
- ".vcd": "application/x-cdlink",
2622
- ".vcf": "text/x-vcard",
2623
- ".vdo": "video/vdo",
2624
- ".vib": "audio/vib",
2625
- ".viv": "video/vivo",
2626
- ".vivo": "video/vivo",
2627
- ".vmd": "application/vocaltec-media-desc",
2628
- ".vmf": "application/vocaltec-media-file",
2629
- ".vmi": "application/x-dreamcast-vms-info",
2630
- ".vms": "application/x-dreamcast-vms",
2631
- ".vox": "audio/voxware",
2632
- ".vqe": "audio/x-twinvq-plugin",
2633
- ".vqf": "audio/x-twinvq",
2634
- ".vql": "audio/x-twinvq",
2635
- ".vre": "x-world/x-vream",
2636
- ".vrml": "x-world/x-vrml",
2637
- ".vrt": "x-world/x-vrt",
2638
- ".vrw": "x-world/x-vream",
2639
- ".vts": "workbook/formulaone",
2640
- ".wav": "audio/x-wav",
2641
- ".wax": "audio/x-ms-wax",
2642
- ".wbmp": "image/vnd.wap.wbmp",
2643
- ".wcm": "application/vnd.ms-works",
2644
- ".wdb": "application/vnd.ms-works",
2645
- ".web": "application/vnd.xara",
2646
- ".wi": "image/wavelet",
2647
- ".wis": "application/x-InstallShield",
2648
- ".wks": "application/vnd.ms-works",
2649
- ".wm": "video/x-ms-wm",
2650
- ".wma": "audio/x-ms-wma",
2651
- ".wmd": "application/x-ms-wmd",
2652
- ".wmf": "application/x-msmetafile",
2653
- ".wml": "text/vnd.wap.wml",
2654
- ".wmlc": "application/vnd.wap.wmlc",
2655
- ".wmls": "text/vnd.wap.wmlscript",
2656
- ".wmlsc": "application/vnd.wap.wmlscriptc",
2657
- ".wmlscript": "text/vnd.wap.wmlscript",
2658
- ".wmv": "audio/x-ms-wmv",
2659
- ".wmx": "video/x-ms-wmx",
2660
- ".wmz": "application/x-ms-wmz",
2661
- ".wpng": "image/x-up-wpng",
2662
- ".wps": "application/vnd.ms-works",
2663
- ".wpt": "x-lml/x-gps",
2664
- ".wri": "application/x-mswrite",
2665
- ".wrl": "x-world/x-vrml",
2666
- ".wrz": "x-world/x-vrml",
2667
- ".ws": "text/vnd.wap.wmlscript",
2668
- ".wsc": "application/vnd.wap.wmlscriptc",
2669
- ".wv": "video/wavelet",
2670
- ".wvx": "video/x-ms-wvx",
2671
- ".wxl": "application/x-wxl",
2672
- ".x-gzip": "application/x-gzip",
2673
- ".xaf": "x-world/x-vrml",
2674
- ".xar": "application/vnd.xara",
2675
- ".xbm": "image/x-xbitmap",
2676
- ".xdm": "application/x-xdma",
2677
- ".xdma": "application/x-xdma",
2678
- ".xdw": "application/vnd.fujixerox.docuworks",
2679
- ".xht": "application/xhtml+xml",
2680
- ".xhtm": "application/xhtml+xml",
2681
- ".xhtml": "application/xhtml+xml",
2682
- ".xla": "application/vnd.ms-excel",
2683
- ".xlc": "application/vnd.ms-excel",
2684
- ".xll": "application/x-excel",
2685
- ".xlm": "application/vnd.ms-excel",
2686
- ".xls": "application/vnd.ms-excel",
2687
- ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
2688
- ".xlt": "application/vnd.ms-excel",
2689
- ".xlw": "application/vnd.ms-excel",
2690
- ".xm": "audio/x-mod",
2691
- ".xml": "text/plain",
2692
- ".xml": "application/xml",
2693
- ".xmz": "audio/x-mod",
2694
- ".xof": "x-world/x-vrml",
2695
- ".xpi": "application/x-xpinstall",
2696
- ".xpm": "image/x-xpixmap",
2697
- ".xsit": "text/xml",
2698
- ".xsl": "text/xml",
2699
- ".xul": "text/xul",
2700
- ".xwd": "image/x-xwindowdump",
2701
- ".xyz": "chemical/x-pdb",
2702
- ".yz1": "application/x-yz1",
2703
- ".z": "application/x-compress",
2704
- ".zac": "application/x-zaurus-zac",
2705
- ".zip": "application/zip",
2706
- ".json": "application/json",
2707
- ".go": "application/go",
2708
- ".properties": "application/properties",
2709
- ".yaml": "application/yaml",
2710
- ".bat": "application/bat",
2711
- ".sh": "application/sh",
2712
- ".vue": "application/vue",
2713
- ".less": "application/less",
2714
- ".sass": "application/sass",
2715
- ".csv": "application/csv",
2716
- ".lua": "application/lua",
2717
- ".apex": "application/apex",
2718
- ".azcli": "application/azcli",
2719
- ".clojure": "application/clojure",
2720
- ".coffee": "application/coffee",
2721
- ".cs": "application/cs",
2722
- ".csp": "application/csp",
2723
- ".dockerfile": "application/dockerfile",
2724
- ".fsharp": "application/fsharp",
2725
- ".handlebars": "text/plain",
2726
- ".ini": "text/plain",
2727
- ".md": "text/plain",
2728
- ".perl": "text/plain",
2729
- ".php": "text/plain",
2730
- ".py": "text/plain",
2731
- ".redis": "text/plain",
2732
- ".conf": "text/conf",
2733
- ".sql": "text/sql"
2734
- }
2735
-
2736
- M.test = function () {
2737
- console.log(privateObj.staticMime[".jssson"] || "aa")
2738
- }
2739
-
2740
- M.getRemoteCacheByUrl = async function (url) {
2741
- if (url in M._globle_cacheMap) {
2742
- return M._globle_cacheMap[url];
2743
- }
2744
- let text = "";
2745
- if (url.startsWith("file:")) {
2746
- text = M.readFile(url.substring(5));
2747
- } else {
2748
- text = await M.get(url);
2749
- }
2750
- console.log("req remote url:", url);
2751
- M._globle_cacheMap[url] = text;
2752
- return text;
2753
- }
2754
-
2755
- M.init = function () {
2756
- /***
2757
- * 下划线命名转为驼峰命名
2758
- */
2759
- String.prototype.underlineToHump = function () {
2760
- var re = /_(\w)/g;
2761
- str = this.replace(re, function ($0, $1) {
2762
- return $1.toUpperCase();
2763
- });
2764
- return str;
2765
- }
2766
-
2767
- /***
2768
- * 驼峰命名转下划线
2769
- */
2770
- String.prototype.humpToUnderline = function () {
2771
- var re = /_(\w)/g;
2772
- str = this.replace(/([A-Z])/g, "_$1").toLowerCase();
2773
- return str;
2774
- }
2775
-
2776
- //首字母变大写
2777
- String.prototype.firstChartoUpper = function () {
2778
- return this.replace(/^([a-z])/g, function (word) {
2779
- return word.replace(word.charAt(0), word.charAt(0).toUpperCase());
2780
- });
2781
- }
2782
- //首字母变小写
2783
- String.prototype.firstChartoLower = function () {
2784
- return this.replace(/^([A-Z])/g, function (word) {
2785
- return word.replace(word.charAt(0), word.charAt(0).toLowerCase());
2786
- });
2787
- }
2788
- //格式化日期
2789
- Date.prototype.format = function (fmt) {
2790
- var o = {
2791
- "M+": this.getMonth() + 1, //月份
2792
- "d+": this.getDate(), //日
2793
- "h+": this.getHours(), //小时
2794
- "m+": this.getMinutes(), //分
2795
- "s+": this.getSeconds(), //秒
2796
- "q+": Math.floor((this.getMonth() + 3) / 3), //季度
2797
- "S": this.getMilliseconds() //毫秒
2798
- };
2799
- if (/(y+)/.test(fmt)) {
2800
- fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
2801
- }
2802
- for (var k in o) {
2803
- if (new RegExp("(" + k + ")").test(fmt)) {
2804
- fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
2805
- }
2806
- }
2807
- return fmt;
2808
- }
2809
-
2810
-
2811
- }
2812
- M.init();
2813
-
2814
- module.exports = M;
2231
+ /**
2232
+ * ----------------------其他工具函数END--------------------------------------------
2233
+ */
2234
+
2235
+ /**
2236
+ * 静态资源对应表
2237
+ */
2238
+ privateObj.staticMime = {
2239
+ ".323": "text/h323",
2240
+ ".3gp": "video/3gpp",
2241
+ ".aab": "application/x-authoware-bin",
2242
+ ".aam": "application/x-authoware-map",
2243
+ ".aas": "application/x-authoware-seg",
2244
+ ".acx": "application/internet-property-stream",
2245
+ ".ai": "application/postscript",
2246
+ ".aif": "audio/x-aiff",
2247
+ ".aifc": "audio/x-aiff",
2248
+ ".aiff": "audio/x-aiff",
2249
+ ".als": "audio/X-Alpha5",
2250
+ ".amc": "application/x-mpeg",
2251
+ ".ani": "application/octet-stream",
2252
+ ".apk": "application/vnd.android.package-archive",
2253
+ ".asc": "text/plain",
2254
+ ".asd": "application/astound",
2255
+ ".asf": "video/x-ms-asf",
2256
+ ".asn": "application/astound",
2257
+ ".asp": "application/x-asap",
2258
+ ".asr": "video/x-ms-asf",
2259
+ ".asx": "video/x-ms-asf",
2260
+ ".au": "audio/basic",
2261
+ ".avb": "application/octet-stream",
2262
+ ".avi": "video/x-msvideo",
2263
+ ".awb": "audio/amr-wb",
2264
+ ".axs": "application/olescript",
2265
+ ".bas": "text/plain",
2266
+ ".bcpio": "application/x-bcpio",
2267
+ ".bin ": "application/octet-stream",
2268
+ ".bld": "application/bld",
2269
+ ".bld2": "application/bld2",
2270
+ ".bmp": "image/bmp",
2271
+ ".bpk": "application/octet-stream",
2272
+ ".bz2": "application/x-bzip2",
2273
+ ".c": "text/plain",
2274
+ ".cal": "image/x-cals",
2275
+ ".cat": "application/vnd.ms-pkiseccat",
2276
+ ".ccn": "application/x-cnc",
2277
+ ".cco": "application/x-cocoa",
2278
+ ".cdf": "application/x-cdf",
2279
+ ".cer": "application/x-x509-ca-cert",
2280
+ ".cgi": "magnus-internal/cgi",
2281
+ ".chat": "application/x-chat",
2282
+ ".class": "application/octet-stream",
2283
+ ".clp": "application/x-msclip",
2284
+ ".cmx": "image/x-cmx",
2285
+ ".co": "application/x-cult3d-object",
2286
+ ".cod": "image/cis-cod",
2287
+ ".conf": "text/plain",
2288
+ ".cpio": "application/x-cpio",
2289
+ ".cpp": "text/plain",
2290
+ ".cpt": "application/mac-compactpro",
2291
+ ".crd": "application/x-mscardfile",
2292
+ ".crl": "application/pkix-crl",
2293
+ ".crt": "application/x-x509-ca-cert",
2294
+ ".csh": "application/x-csh",
2295
+ ".csm": "chemical/x-csml",
2296
+ ".csml": "chemical/x-csml",
2297
+ ".css": "text/css",
2298
+ ".cur": "application/octet-stream",
2299
+ ".dcm": "x-lml/x-evm",
2300
+ ".dcr": "application/x-director",
2301
+ ".dcx": "image/x-dcx",
2302
+ ".der": "application/x-x509-ca-cert",
2303
+ ".dhtml": "text/html",
2304
+ ".dir": "application/x-director",
2305
+ ".dll": "application/x-msdownload",
2306
+ ".dmg": "application/octet-stream",
2307
+ ".dms": "application/octet-stream",
2308
+ ".doc": "application/msword",
2309
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
2310
+ ".dot": "application/msword",
2311
+ ".dvi": "application/x-dvi",
2312
+ ".dwf": "drawing/x-dwf",
2313
+ ".dwg": "application/x-autocad",
2314
+ ".dxf": "application/x-autocad",
2315
+ ".dxr": "application/x-director",
2316
+ ".ebk": "application/x-expandedbook",
2317
+ ".emb": "chemical/x-embl-dl-nucleotide",
2318
+ ".embl": "chemical/x-embl-dl-nucleotide",
2319
+ ".eps": "application/postscript",
2320
+ ".epub": "application/epub+zip",
2321
+ ".eri": "image/x-eri",
2322
+ ".es": "audio/echospeech",
2323
+ ".esl": "audio/echospeech",
2324
+ ".etc": "application/x-earthtime",
2325
+ ".etx": "text/x-setext",
2326
+ ".evm": "x-lml/x-evm",
2327
+ ".evy": "application/envoy",
2328
+ ".exe": "application/octet-stream",
2329
+ ".fh4": "image/x-freehand",
2330
+ ".fh5": "image/x-freehand",
2331
+ ".fhc": "image/x-freehand",
2332
+ ".fif": "application/fractals",
2333
+ ".flr": "x-world/x-vrml",
2334
+ ".flv": "flv-application/octet-stream",
2335
+ ".fm": "application/x-maker",
2336
+ ".fpx": "image/x-fpx",
2337
+ ".fvi": "video/isivideo",
2338
+ ".gau": "chemical/x-gaussian-input",
2339
+ ".gca": "application/x-gca-compressed",
2340
+ ".gdb": "x-lml/x-gdb",
2341
+ ".gif": "image/gif",
2342
+ ".gps": "application/x-gps",
2343
+ ".gtar": "application/x-gtar",
2344
+ ".gz": "application/x-gzip",
2345
+ ".h": "text/plain",
2346
+ ".hdf": "application/x-hdf",
2347
+ ".hdm": "text/x-hdml",
2348
+ ".hdml": "text/x-hdml",
2349
+ ".hlp": "application/winhlp",
2350
+ ".hqx": "application/mac-binhex40",
2351
+ ".hta": "application/hta",
2352
+ ".htc": "text/x-component",
2353
+ ".htm": "text/html",
2354
+ ".html": "text/html",
2355
+ ".hts": "text/html",
2356
+ ".htt": "text/webviewhtml",
2357
+ ".ice": "x-conference/x-cooltalk",
2358
+ ".ico": "image/x-icon",
2359
+ ".ief": "image/ief",
2360
+ ".ifm": "image/gif",
2361
+ ".ifs": "image/ifs",
2362
+ ".iii": "application/x-iphone",
2363
+ ".imy": "audio/melody",
2364
+ ".ins": "application/x-internet-signup",
2365
+ ".ips": "application/x-ipscript",
2366
+ ".ipx": "application/x-ipix",
2367
+ ".isp": "application/x-internet-signup",
2368
+ ".it": "audio/x-mod",
2369
+ ".itz": "audio/x-mod",
2370
+ ".ivr": "i-world/i-vrml",
2371
+ ".j2k": "image/j2k",
2372
+ ".jad": "text/vnd.sun.j2me.app-descriptor",
2373
+ ".jam": "application/x-jam",
2374
+ ".jar": "application/java-archive",
2375
+ ".java": "text/plain",
2376
+ ".jfif": "image/pipeg",
2377
+ ".jnlp": "application/x-java-jnlp-file",
2378
+ ".jpe": "image/jpeg",
2379
+ ".jpeg": "image/jpeg",
2380
+ ".jpg": "image/jpeg",
2381
+ ".jpz": "image/jpeg",
2382
+ ".js": "application/javascript",
2383
+ ".jsx": "application/javascript",
2384
+ ".woff":" application/x-font-woff",
2385
+ ".woff2":" application/x-font-woff",
2386
+ ".jwc": "application/jwc",
2387
+ ".kjx": "application/x-kjx",
2388
+ ".lak": "x-lml/x-lak",
2389
+ ".latex": "application/x-latex",
2390
+ ".lcc": "application/fastman",
2391
+ ".lcl": "application/x-digitalloca",
2392
+ ".lcr": "application/x-digitalloca",
2393
+ ".lgh": "application/lgh",
2394
+ ".lha": "application/octet-stream",
2395
+ ".lml": "x-lml/x-lml",
2396
+ ".lmlpack": "x-lml/x-lmlpack",
2397
+ ".log": "text/plain",
2398
+ ".lsf": "video/x-la-asf",
2399
+ ".lsx": "video/x-la-asf",
2400
+ ".lzh": "application/octet-stream",
2401
+ ".m13": "application/x-msmediaview",
2402
+ ".m14": "application/x-msmediaview",
2403
+ ".m15": "audio/x-mod",
2404
+ ".m3u": "audio/x-mpegurl",
2405
+ ".m3url": "audio/x-mpegurl",
2406
+ ".m4a": "audio/mp4a-latm",
2407
+ ".m4b": "audio/mp4a-latm",
2408
+ ".m4p": "audio/mp4a-latm",
2409
+ ".m4u": "video/vnd.mpegurl",
2410
+ ".m4v": "video/x-m4v",
2411
+ ".ma1": "audio/ma1",
2412
+ ".ma2": "audio/ma2",
2413
+ ".ma3": "audio/ma3",
2414
+ ".ma5": "audio/ma5",
2415
+ ".man": "application/x-troff-man",
2416
+ ".map": "magnus-internal/imagemap",
2417
+ ".mbd": "application/mbedlet",
2418
+ ".mct": "application/x-mascot",
2419
+ ".mdb": "application/x-msaccess",
2420
+ ".mdz": "audio/x-mod",
2421
+ ".me": "application/x-troff-me",
2422
+ ".mel": "text/x-vmel",
2423
+ ".mht": "message/rfc822",
2424
+ ".mhtml": "message/rfc822",
2425
+ ".mi": "application/x-mif",
2426
+ ".mid": "audio/mid",
2427
+ ".midi": "audio/midi",
2428
+ ".mif": "application/x-mif",
2429
+ ".mil": "image/x-cals",
2430
+ ".mio": "audio/x-mio",
2431
+ ".mmf": "application/x-skt-lbs",
2432
+ ".mng": "video/x-mng",
2433
+ ".mny": "application/x-msmoney",
2434
+ ".moc": "application/x-mocha",
2435
+ ".mocha": "application/x-mocha",
2436
+ ".mod": "audio/x-mod",
2437
+ ".mof": "application/x-yumekara",
2438
+ ".mol": "chemical/x-mdl-molfile",
2439
+ ".mop": "chemical/x-mopac-input",
2440
+ ".mov": "video/quicktime",
2441
+ ".movie": "video/x-sgi-movie",
2442
+ ".mp2": "video/mpeg",
2443
+ ".mp3": "audio/mpeg",
2444
+ ".mp4": "video/mp4",
2445
+ ".mpa": "video/mpeg",
2446
+ ".mpc": "application/vnd.mpohun.certificate",
2447
+ ".mpe": "video/mpeg",
2448
+ ".mpeg": "video/mpeg",
2449
+ ".mpg": "video/mpeg",
2450
+ ".mpg4": "video/mp4",
2451
+ ".mpga": "audio/mpeg",
2452
+ ".mpn": "application/vnd.mophun.application",
2453
+ ".mpp": "application/vnd.ms-project",
2454
+ ".mps": "application/x-mapserver",
2455
+ ".mpv2": "video/mpeg",
2456
+ ".mrl": "text/x-mrml",
2457
+ ".mrm": "application/x-mrm",
2458
+ ".ms": "application/x-troff-ms",
2459
+ ".msg": "application/vnd.ms-outlook",
2460
+ ".mts": "application/metastream",
2461
+ ".mtx": "application/metastream",
2462
+ ".mtz": "application/metastream",
2463
+ ".mvb": "application/x-msmediaview",
2464
+ ".mzv": "application/metastream",
2465
+ ".nar": "application/zip",
2466
+ ".nbmp": "image/nbmp",
2467
+ ".nc": "application/x-netcdf",
2468
+ ".ndb": "x-lml/x-ndb",
2469
+ ".ndwn": "application/ndwn",
2470
+ ".nif": "application/x-nif",
2471
+ ".nmz": "application/x-scream",
2472
+ ".nokia-op-logo": "image/vnd.nok-oplogo-color",
2473
+ ".npx": "application/x-netfpx",
2474
+ ".nsnd": "audio/nsnd",
2475
+ ".nva": "application/x-neva1",
2476
+ ".nws": "message/rfc822",
2477
+ ".oda": "application/oda",
2478
+ ".ogg": "audio/ogg",
2479
+ ".oom": "application/x-AtlasMate-Plugin",
2480
+ ".p10": "application/pkcs10",
2481
+ ".p12": "application/x-pkcs12",
2482
+ ".p7b": "application/x-pkcs7-certificates",
2483
+ ".p7c": "application/x-pkcs7-mime",
2484
+ ".p7m": "application/x-pkcs7-mime",
2485
+ ".p7r": "application/x-pkcs7-certreqresp",
2486
+ ".p7s": "application/x-pkcs7-signature",
2487
+ ".pac": "audio/x-pac",
2488
+ ".pae": "audio/x-epac",
2489
+ ".pan": "application/x-pan",
2490
+ ".pbm": "image/x-portable-bitmap",
2491
+ ".pcx": "image/x-pcx",
2492
+ ".pda": "image/x-pda",
2493
+ ".pdb": "chemical/x-pdb",
2494
+ ".pdf": "application/pdf",
2495
+ ".pfr": "application/font-tdpfr",
2496
+ ".pfx": "application/x-pkcs12",
2497
+ ".pgm": "image/x-portable-graymap",
2498
+ ".pict": "image/x-pict",
2499
+ ".pko": "application/ynd.ms-pkipko",
2500
+ ".pm": "application/x-perl",
2501
+ ".pma": "application/x-perfmon",
2502
+ ".pmc": "application/x-perfmon",
2503
+ ".pmd": "application/x-pmd",
2504
+ ".pml": "application/x-perfmon",
2505
+ ".pmr": "application/x-perfmon",
2506
+ ".pmw": "application/x-perfmon",
2507
+ ".png": "image/png",
2508
+ ".pnm": "image/x-portable-anymap",
2509
+ ".pnz": "image/png",
2510
+ ".pot,": "application/vnd.ms-powerpoint",
2511
+ ".ppm": "image/x-portable-pixmap",
2512
+ ".pps": "application/vnd.ms-powerpoint",
2513
+ ".ppt": "application/vnd.ms-powerpoint",
2514
+ ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
2515
+ ".pqf": "application/x-cprplayer",
2516
+ ".pqi": "application/cprplayer",
2517
+ ".prc": "application/x-prc",
2518
+ ".prf": "application/pics-rules",
2519
+ ".prop": "text/plain",
2520
+ ".proxy": "application/x-ns-proxy-autoconfig",
2521
+ ".ps": "application/postscript",
2522
+ ".ptlk": "application/listenup",
2523
+ ".pub": "application/x-mspublisher",
2524
+ ".pvx": "video/x-pv-pvx",
2525
+ ".qcp": "audio/vnd.qcelp",
2526
+ ".qt": "video/quicktime",
2527
+ ".qti": "image/x-quicktime",
2528
+ ".qtif": "image/x-quicktime",
2529
+ ".r3t": "text/vnd.rn-realtext3d",
2530
+ ".ra": "audio/x-pn-realaudio",
2531
+ ".ram": "audio/x-pn-realaudio",
2532
+ ".rar": "application/octet-stream",
2533
+ ".ras": "image/x-cmu-raster",
2534
+ ".rc": "text/plain",
2535
+ ".rdf": "application/rdf+xml",
2536
+ ".rf": "image/vnd.rn-realflash",
2537
+ ".rgb": "image/x-rgb",
2538
+ ".rlf": "application/x-richlink",
2539
+ ".rm": "audio/x-pn-realaudio",
2540
+ ".rmf": "audio/x-rmf",
2541
+ ".rmi": "audio/mid",
2542
+ ".rmm": "audio/x-pn-realaudio",
2543
+ ".rmvb": "audio/x-pn-realaudio",
2544
+ ".rnx": "application/vnd.rn-realplayer",
2545
+ ".roff": "application/x-troff",
2546
+ ".rp": "image/vnd.rn-realpix",
2547
+ ".rpm": "audio/x-pn-realaudio-plugin",
2548
+ ".rt": "text/vnd.rn-realtext",
2549
+ ".rte": "x-lml/x-gps",
2550
+ ".rtf": "application/rtf",
2551
+ ".rtg": "application/metastream",
2552
+ ".rtx": "text/richtext",
2553
+ ".rv": "video/vnd.rn-realvideo",
2554
+ ".rwc": "application/x-rogerwilco",
2555
+ ".s3m": "audio/x-mod",
2556
+ ".s3z": "audio/x-mod",
2557
+ ".sca": "application/x-supercard",
2558
+ ".scd": "application/x-msschedule",
2559
+ ".sct": "text/scriptlet",
2560
+ ".sdf": "application/e-score",
2561
+ ".sea": "application/x-stuffit",
2562
+ ".setpay": "application/set-payment-initiation",
2563
+ ".setreg": "application/set-registration-initiation",
2564
+ ".sgm": "text/x-sgml",
2565
+ ".sgml": "text/x-sgml",
2566
+ ".sh": "application/x-sh",
2567
+ ".shar": "application/x-shar",
2568
+ ".shtml": "magnus-internal/parsed-html",
2569
+ ".shw": "application/presentations",
2570
+ ".si6": "image/si6",
2571
+ ".si7": "image/vnd.stiwap.sis",
2572
+ ".si9": "image/vnd.lgtwap.sis",
2573
+ ".sis": "application/vnd.symbian.install",
2574
+ ".sit": "application/x-stuffit",
2575
+ ".skd": "application/x-Koan",
2576
+ ".skm": "application/x-Koan",
2577
+ ".skp": "application/x-Koan",
2578
+ ".skt": "application/x-Koan",
2579
+ ".slc": "application/x-salsa",
2580
+ ".smd": "audio/x-smd",
2581
+ ".smi": "application/smil",
2582
+ ".smil": "application/smil",
2583
+ ".smp": "application/studiom",
2584
+ ".smz": "audio/x-smd",
2585
+ ".snd": "audio/basic",
2586
+ ".spc": "application/x-pkcs7-certificates",
2587
+ ".spl": "application/futuresplash",
2588
+ ".spr": "application/x-sprite",
2589
+ ".sprite": "application/x-sprite",
2590
+ ".sdp": "application/sdp",
2591
+ ".spt": "application/x-spt",
2592
+ ".src": "application/x-wais-source",
2593
+ ".sst": "application/vnd.ms-pkicertstore",
2594
+ ".stk": "application/hyperstudio",
2595
+ ".stl": "application/vnd.ms-pkistl",
2596
+ ".stm": "text/html",
2597
+ ".svg": "image/svg+xml",
2598
+ ".sv4cpio": "application/x-sv4cpio",
2599
+ ".sv4crc": "application/x-sv4crc",
2600
+ ".svf": "image/vnd",
2601
+ ".svh": "image/svh",
2602
+ ".svr": "x-world/x-svr",
2603
+ ".swf": "application/x-shockwave-flash",
2604
+ ".swfl": "application/x-shockwave-flash",
2605
+ ".t": "application/x-troff",
2606
+ ".tad": "application/octet-stream",
2607
+ ".talk": "text/x-speech",
2608
+ ".tar": "application/x-tar",
2609
+ ".taz": "application/x-tar",
2610
+ ".tbp": "application/x-timbuktu",
2611
+ ".tbt": "application/x-timbuktu",
2612
+ ".tcl": "application/x-tcl",
2613
+ ".tex": "application/x-tex",
2614
+ ".texi": "application/x-texinfo",
2615
+ ".texinfo": "application/x-texinfo",
2616
+ ".tgz": "application/x-compressed",
2617
+ ".thm": "application/vnd.eri.thm",
2618
+ ".tif": "image/tiff",
2619
+ ".tiff": "image/tiff",
2620
+ ".tki": "application/x-tkined",
2621
+ ".tkined": "application/x-tkined",
2622
+ ".toc": "application/toc",
2623
+ ".toy": "image/toy",
2624
+ ".tr": "application/x-troff",
2625
+ ".trk": "x-lml/x-gps",
2626
+ ".trm": "application/x-msterminal",
2627
+ ".tsi": "audio/tsplayer",
2628
+ ".tsp": "application/dsptype",
2629
+ ".tsv": "text/tab-separated-values",
2630
+ ".ttf": "application/octet-stream",
2631
+ ".ttz": "application/t-time",
2632
+ ".txt": "text/plain",
2633
+ ".uls": "text/iuls",
2634
+ ".ult": "audio/x-mod",
2635
+ ".ustar": "application/x-ustar",
2636
+ ".uu": "application/x-uuencode",
2637
+ ".uue": "application/x-uuencode",
2638
+ ".vcd": "application/x-cdlink",
2639
+ ".vcf": "text/x-vcard",
2640
+ ".vdo": "video/vdo",
2641
+ ".vib": "audio/vib",
2642
+ ".viv": "video/vivo",
2643
+ ".vivo": "video/vivo",
2644
+ ".vmd": "application/vocaltec-media-desc",
2645
+ ".vmf": "application/vocaltec-media-file",
2646
+ ".vmi": "application/x-dreamcast-vms-info",
2647
+ ".vms": "application/x-dreamcast-vms",
2648
+ ".vox": "audio/voxware",
2649
+ ".vqe": "audio/x-twinvq-plugin",
2650
+ ".vqf": "audio/x-twinvq",
2651
+ ".vql": "audio/x-twinvq",
2652
+ ".vre": "x-world/x-vream",
2653
+ ".vrml": "x-world/x-vrml",
2654
+ ".vrt": "x-world/x-vrt",
2655
+ ".vrw": "x-world/x-vream",
2656
+ ".vts": "workbook/formulaone",
2657
+ ".wav": "audio/x-wav",
2658
+ ".wax": "audio/x-ms-wax",
2659
+ ".wbmp": "image/vnd.wap.wbmp",
2660
+ ".wcm": "application/vnd.ms-works",
2661
+ ".wdb": "application/vnd.ms-works",
2662
+ ".web": "application/vnd.xara",
2663
+ ".wi": "image/wavelet",
2664
+ ".wis": "application/x-InstallShield",
2665
+ ".wks": "application/vnd.ms-works",
2666
+ ".wm": "video/x-ms-wm",
2667
+ ".wma": "audio/x-ms-wma",
2668
+ ".wmd": "application/x-ms-wmd",
2669
+ ".wmf": "application/x-msmetafile",
2670
+ ".wml": "text/vnd.wap.wml",
2671
+ ".wmlc": "application/vnd.wap.wmlc",
2672
+ ".wmls": "text/vnd.wap.wmlscript",
2673
+ ".wmlsc": "application/vnd.wap.wmlscriptc",
2674
+ ".wmlscript": "text/vnd.wap.wmlscript",
2675
+ ".wmv": "audio/x-ms-wmv",
2676
+ ".wmx": "video/x-ms-wmx",
2677
+ ".wmz": "application/x-ms-wmz",
2678
+ ".wpng": "image/x-up-wpng",
2679
+ ".wps": "application/vnd.ms-works",
2680
+ ".wpt": "x-lml/x-gps",
2681
+ ".wri": "application/x-mswrite",
2682
+ ".wrl": "x-world/x-vrml",
2683
+ ".wrz": "x-world/x-vrml",
2684
+ ".ws": "text/vnd.wap.wmlscript",
2685
+ ".wsc": "application/vnd.wap.wmlscriptc",
2686
+ ".wv": "video/wavelet",
2687
+ ".wvx": "video/x-ms-wvx",
2688
+ ".wxl": "application/x-wxl",
2689
+ ".x-gzip": "application/x-gzip",
2690
+ ".xaf": "x-world/x-vrml",
2691
+ ".xar": "application/vnd.xara",
2692
+ ".xbm": "image/x-xbitmap",
2693
+ ".xdm": "application/x-xdma",
2694
+ ".xdma": "application/x-xdma",
2695
+ ".xdw": "application/vnd.fujixerox.docuworks",
2696
+ ".xht": "application/xhtml+xml",
2697
+ ".xhtm": "application/xhtml+xml",
2698
+ ".xhtml": "application/xhtml+xml",
2699
+ ".xla": "application/vnd.ms-excel",
2700
+ ".xlc": "application/vnd.ms-excel",
2701
+ ".xll": "application/x-excel",
2702
+ ".xlm": "application/vnd.ms-excel",
2703
+ ".xls": "application/vnd.ms-excel",
2704
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
2705
+ ".xlt": "application/vnd.ms-excel",
2706
+ ".xlw": "application/vnd.ms-excel",
2707
+ ".xm": "audio/x-mod",
2708
+ ".xml": "text/plain",
2709
+ ".xml": "application/xml",
2710
+ ".xmz": "audio/x-mod",
2711
+ ".xof": "x-world/x-vrml",
2712
+ ".xpi": "application/x-xpinstall",
2713
+ ".xpm": "image/x-xpixmap",
2714
+ ".xsit": "text/xml",
2715
+ ".xsl": "text/xml",
2716
+ ".xul": "text/xul",
2717
+ ".xwd": "image/x-xwindowdump",
2718
+ ".xyz": "chemical/x-pdb",
2719
+ ".yz1": "application/x-yz1",
2720
+ ".z": "application/x-compress",
2721
+ ".zac": "application/x-zaurus-zac",
2722
+ ".zip": "application/zip",
2723
+ ".json": "application/json",
2724
+ ".go": "application/go",
2725
+ ".properties": "application/properties",
2726
+ ".yaml": "application/yaml",
2727
+ ".bat": "application/bat",
2728
+ ".sh": "application/sh",
2729
+ ".vue": "application/vue",
2730
+ ".less": "application/less",
2731
+ ".sass": "application/sass",
2732
+ ".csv": "application/csv",
2733
+ ".lua": "application/lua",
2734
+ ".apex": "application/apex",
2735
+ ".azcli": "application/azcli",
2736
+ ".clojure": "application/clojure",
2737
+ ".coffee": "application/coffee",
2738
+ ".cs": "application/cs",
2739
+ ".csp": "application/csp",
2740
+ ".dockerfile": "application/dockerfile",
2741
+ ".fsharp": "application/fsharp",
2742
+ ".handlebars": "text/plain",
2743
+ ".ini": "text/plain",
2744
+ ".md": "text/plain",
2745
+ ".perl": "text/plain",
2746
+ ".php": "text/plain",
2747
+ ".py": "text/plain",
2748
+ ".redis": "text/plain",
2749
+ ".conf": "text/conf",
2750
+ ".sql": "text/sql"
2751
+ }
2752
+
2753
+ M.test = function () {
2754
+ console.log(privateObj.staticMime[".jssson"] || "aa")
2755
+ }
2756
+
2757
+ M.getRemoteCacheByUrl = async function (url) {
2758
+ if (url in M._globle_cacheMap) {
2759
+ return M._globle_cacheMap[url];
2760
+ }
2761
+ let text = "";
2762
+ if (url.startsWith("file:")) {
2763
+ text = M.readFile(url.substring(5));
2764
+ } else {
2765
+ text = await M.get(url);
2766
+ }
2767
+ console.log("req remote url:", url);
2768
+ M._globle_cacheMap[url] = text;
2769
+ return text;
2770
+ }
2771
+
2772
+ M.init = function () {
2773
+ /***
2774
+ * 下划线命名转为驼峰命名
2775
+ */
2776
+ String.prototype.underlineToHump = function () {
2777
+ var re = /_(\w)/g;
2778
+ str = this.replace(re, function ($0, $1) {
2779
+ return $1.toUpperCase();
2780
+ });
2781
+ return str;
2782
+ }
2783
+
2784
+ /***
2785
+ * 驼峰命名转下划线
2786
+ */
2787
+ String.prototype.humpToUnderline = function () {
2788
+ var re = /_(\w)/g;
2789
+ str = this.replace(/([A-Z])/g, "_$1").toLowerCase();
2790
+ return str;
2791
+ }
2792
+
2793
+ //首字母变大写
2794
+ String.prototype.firstChartoUpper = function () {
2795
+ return this.replace(/^([a-z])/g, function (word) {
2796
+ return word.replace(word.charAt(0), word.charAt(0).toUpperCase());
2797
+ });
2798
+ }
2799
+ //首字母变小写
2800
+ String.prototype.firstChartoLower = function () {
2801
+ return this.replace(/^([A-Z])/g, function (word) {
2802
+ return word.replace(word.charAt(0), word.charAt(0).toLowerCase());
2803
+ });
2804
+ }
2805
+ //格式化日期
2806
+ Date.prototype.format = function (fmt) {
2807
+ var o = {
2808
+ "M+": this.getMonth() + 1, //月份
2809
+ "d+": this.getDate(), //日
2810
+ "h+": this.getHours(), //小时
2811
+ "m+": this.getMinutes(), //分
2812
+ "s+": this.getSeconds(), //秒
2813
+ "q+": Math.floor((this.getMonth() + 3) / 3), //季度
2814
+ "S": this.getMilliseconds() //毫秒
2815
+ };
2816
+ if (/(y+)/.test(fmt)) {
2817
+ fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
2818
+ }
2819
+ for (var k in o) {
2820
+ if (new RegExp("(" + k + ")").test(fmt)) {
2821
+ fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
2822
+ }
2823
+ }
2824
+ return fmt;
2825
+ }
2826
+
2827
+
2828
+ }
2829
+ M.init();
2830
+
2831
+ global.M=M;
2832
+ global.MIO=M.IO;
2833
+
2834
+ module.exports = M;