ming_node 2.2.6 → 2.5.0

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