ming_node 2.3.0 → 2.8.0

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