ming_node 3.0.1 → 3.0.3

Sign up to get free protection for your applications and to get access to all the features.
package/README.md CHANGED
@@ -220,3 +220,10 @@ https://minglie.github.io/os/ming_node/
220
220
  # ming_node使用文档
221
221
 
222
222
  https://www.yuque.com/docs/share/e1f16015-0719-4ffd-9464-a35610389153?# 《ming_node》
223
+
224
+
225
+ # ming_node使用文档
226
+
227
+ https://www.yuque.com/docs/share/e1f16015-0719-4ffd-9464-a35610389153?# 《ming_node》
228
+
229
+ https://unpkg.com/minglitlie-test/h5/index.html
@@ -0,0 +1,3 @@
1
+ a,b
2
+ 3,"3,3"
3
+ 3,5.22
@@ -9,7 +9,7 @@ app.set("connect",(req,res)=>{
9
9
 
10
10
  app.set("data",(req,res)=>{
11
11
 
12
- console.log(req.params)
12
+ console.log(req.params+"")
13
13
 
14
14
  res.send("123")
15
15
 
@@ -3,7 +3,7 @@ app=new UdpServer();
3
3
  app.listen(9999)
4
4
 
5
5
  app.set("message", (req,res)=>{
6
- console.log(req.params)
6
+ console.log(req.params+"")
7
7
  res.send("AAA")
8
8
  })
9
9
 
@@ -0,0 +1,11 @@
1
+ M=require("../index.js")
2
+
3
+
4
+ async function main(){
5
+ await M.readCsvLine("./a.csv",l=>{
6
+ console.log(l)
7
+ })
8
+ console.log("结束")
9
+ }
10
+
11
+ main()
@@ -0,0 +1,3 @@
1
+ {
2
+ "A": 77
3
+ }
@@ -0,0 +1,3 @@
1
+ {
2
+ "A": 77 //aa
3
+ }
@@ -1,8 +1,5 @@
1
- var M=require("../index");
1
+ M=require("../index.js")
2
2
 
3
3
  app=M.server()
4
- app.listen(8888)
5
4
 
6
- app.get(["/h15","/h16","/h18888"],(req,res)=>{
7
- res.send("BBBBXXXEEEEE")
8
- })
5
+ app.listen(8888)
@@ -0,0 +1,75 @@
1
+ const ExcelJS = require('exceljs');
2
+
3
+ class MingExcelTool {
4
+ worksheet;
5
+ constructor(path,indexOrName) {
6
+ this.path=path;
7
+ this.indexOrName=indexOrName;
8
+ }
9
+ async init(){
10
+ const workbook = new ExcelJS.Workbook();
11
+ this.workbook=workbook;
12
+ await workbook.xlsx.readFile(this.path);
13
+ this.worksheet = workbook.getWorksheet(this.indexOrName);
14
+ }
15
+
16
+ getCell(cellName){
17
+ const cell =this.worksheet.getCell(cellName);
18
+ return cell.value;
19
+ }
20
+
21
+ getColumn(indexOrKey){
22
+ const col =this.worksheet.getColumn(indexOrKey);
23
+ let r=[];
24
+ col.eachCell((cell, rowNumber) => {
25
+ if( "object"==typeof cell.value ){
26
+ if(cell.value==null){
27
+ r.push("");
28
+ }else{
29
+ r.push(cell.value.result);
30
+ }
31
+ }else {
32
+ r.push(cell.value);
33
+ }
34
+ });
35
+ return r;
36
+ }
37
+
38
+ getRow(indexOrKey){
39
+ const col =this.worksheet.getRow(indexOrKey);
40
+ let r=[];
41
+ col.eachCell((cell, rowNumber) => {
42
+ if( "object"==typeof cell.value ){
43
+ r.push(cell.value.result);
44
+ }else {
45
+ r.push(cell.value);
46
+ }
47
+ });
48
+ return r;
49
+ }
50
+
51
+ setCell(cellName,val){
52
+ this.worksheet.getCell(cellName).value = val;
53
+ }
54
+
55
+ async save(fileName){
56
+ await this.workbook.xlsx.writeFile(fileName);
57
+ }
58
+
59
+ }
60
+
61
+
62
+ function test(){
63
+ const me= new MingExcelTool('hq.xlsx',1 );
64
+ async function main(){
65
+ await me.init();
66
+ let c= me.getColumn(3);
67
+ me.setCell("H4","wer")
68
+ await me.save("D:/ming.xlsx")
69
+ console.log(c);
70
+ }
71
+ main()
72
+ }
73
+
74
+ test()
75
+ module.exports = MingExcelTool;
package/index.js CHANGED
@@ -3,19 +3,19 @@
3
3
  * By : Minglie
4
4
  * QQ: 934031452
5
5
  * Date :2021.12.01
6
- * version :2.9.9
6
+ * version :3.0.3
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 = {};
8
+ const http = require('http');
9
+ const https = require('https');
10
+ const url_module = require('url');
11
+ const querystring = require('querystring');
12
+ const fs = require('fs');
13
+ const path = require('path');
14
+ const child_process = require('child_process');
15
+ const EventEmitter = require('events').EventEmitter;
16
+ const event = new EventEmitter();
17
+ const privateObj = {};//本文件私有对象
18
+ const M = {};
19
19
  M.privateObj=privateObj;
20
20
  M.sessions = {}//保存session
21
21
  M.con_display_status_enable = false;//是否显示响应状态码
@@ -134,9 +134,9 @@ M.get = function (url, callback, data, headers) {
134
134
  }
135
135
  //合并请求头
136
136
  headers = privateObj.getFunctionOrObjResult(M.reqComHeaders, headers)
137
- var html = '';
138
- var urlObj = url_module.parse(url)
139
- var options = {
137
+ let html = '';
138
+ let urlObj = url_module.parse(url)
139
+ let options = {
140
140
  hostname: urlObj.hostname,
141
141
  port: urlObj.port,
142
142
  path: urlObj.path + getData,
@@ -159,7 +159,7 @@ M.get = function (url, callback, data, headers) {
159
159
  if (options == false) {
160
160
  return;
161
161
  }
162
- var req = reqHttp.request(options, function (res) {
162
+ let req = reqHttp.request(options, function (res) {
163
163
  if (M.con_display_status_enable) console.log('STATUS:' + res.statusCode);
164
164
  if (global.debug && res.statusCode != 200) {
165
165
  while (1) {
@@ -189,8 +189,6 @@ M.get = function (url, callback, data, headers) {
189
189
  });
190
190
  req.on('error', function (err) {
191
191
  reject(err);
192
- console.error(err);
193
-
194
192
  });
195
193
  req.end();
196
194
  })
@@ -206,10 +204,10 @@ M._request = function (url, callback, data, headers,methed) {
206
204
  }
207
205
 
208
206
  url = privateObj.appendDataToUrl(url, M.reqComQueryparams);
209
- var html = '';
210
- var urlObj = url_module.parse(url)
207
+ let html = '';
208
+ let urlObj = url_module.parse(url)
211
209
  //发送 http Post 请求
212
- var postData = querystring.stringify(data);
210
+ let postData = querystring.stringify(data);
213
211
  if( headers["Content-Type"]==undefined){
214
212
  headers["Content-Type"] ="application/json";
215
213
  }
@@ -225,7 +223,7 @@ M._request = function (url, callback, data, headers,methed) {
225
223
 
226
224
  //合并请求头
227
225
  headers = privateObj.getFunctionOrObjResult(M.reqComHeaders, headers)
228
- var options = {
226
+ let options = {
229
227
  hostname: urlObj.hostname,
230
228
  port: urlObj.port,
231
229
  path: urlObj.path,
@@ -244,7 +242,7 @@ M._request = function (url, callback, data, headers,methed) {
244
242
  }
245
243
 
246
244
  return new Promise((resolve, reject) => {
247
- var req = reqHttp.request(options, function (res) {
245
+ let req = reqHttp.request(options, function (res) {
248
246
  options = M.httpBefore(options);
249
247
  if (options == false) {
250
248
  return;
@@ -276,8 +274,7 @@ M._request = function (url, callback, data, headers,methed) {
276
274
  });
277
275
 
278
276
  req.on('error', function (err) {
279
- console.error(err);
280
- throw err;
277
+ reject(err);
281
278
  });
282
279
  if(methed !="GET") req.write(postData);
283
280
  req.end();
@@ -296,10 +293,10 @@ M.postJson = function (url, callback, data, headers) {
296
293
  };
297
294
  }
298
295
  url = privateObj.appendDataToUrl(url, M.reqComQueryparams);
299
- var html = '';
300
- var urlObj = url_module.parse(url)
296
+ let html = '';
297
+ let urlObj = url_module.parse(url)
301
298
  //发送 http Post 请求
302
- var postData = JSON.stringify(data);
299
+ let postData = JSON.stringify(data);
303
300
  if (!headers) {
304
301
  headers = {
305
302
  'Content-Type': 'application/json; ' +
@@ -309,7 +306,7 @@ M.postJson = function (url, callback, data, headers) {
309
306
  }
310
307
  //合并请求头
311
308
  headers = privateObj.getFunctionOrObjResult(M.reqComHeaders, headers)
312
- var options = {
309
+ let options = {
313
310
  hostname: urlObj.hostname,
314
311
  port: urlObj.port,
315
312
  path: urlObj.path,
@@ -329,7 +326,7 @@ M.postJson = function (url, callback, data, headers) {
329
326
 
330
327
  return new Promise((resolve, reject) => {
331
328
 
332
- var req = reqHttp.request(options, function (res) {
329
+ let req = reqHttp.request(options, function (res) {
333
330
  options = M.httpBefore(options);
334
331
  if (options == false) {
335
332
  return;
@@ -361,8 +358,7 @@ M.postJson = function (url, callback, data, headers) {
361
358
  });
362
359
 
363
360
  req.on('error', function (err) {
364
- console.error(err);
365
- throw err;
361
+ reject(err);
366
362
  });
367
363
  req.write(postData);
368
364
  req.end();
@@ -393,7 +389,7 @@ M.require =async function (url,noCache) {
393
389
  console.log("req require remote url:", url);
394
390
  let promise = new Promise(function (reslove, reject) {
395
391
  require(ht).get(url, function (req, res) {
396
- var d = '';
392
+ let d = '';
397
393
  req.on('data', (data) => {
398
394
  d += data;
399
395
  });
@@ -444,7 +440,7 @@ M.import=async function (url,callback){
444
440
  *下载图片
445
441
  */
446
442
  M.download =async function (url, file) {
447
- var func = http;
443
+ let func = http;
448
444
  if (url.indexOf("https") >= 0) {
449
445
  func = https;
450
446
  }
@@ -464,23 +460,24 @@ M.download =async function (url, file) {
464
460
  *下载所有图片
465
461
  */
466
462
  M.downloadAllImg = function (url, file, callback) {
467
- var urlObj = url_module.parse(url)
468
- var options = {
463
+ let urlObj = url_module.parse(url)
464
+ let options = {
469
465
  hostname: urlObj.hostname,
470
466
  }
471
- var func = http;
467
+ let func = http;
472
468
  if (url.indexOf("https") >= 0) {
473
469
  func = https;
474
470
  }
475
- var req = func.request(options, function (res) {
471
+ let req = func.request(options, function (res) {
472
+ res.setEncoding('utf-8');
476
473
  res.on('data', function (data) {
477
474
  //Buffer
478
- var string = data.toString();
479
- var rule = /https?:\/\/.[^"]+\.(png|jpg|gif|jpeg)/gi;
480
- var ary = string.match(rule); //拿到所有jpg结尾的链接集合
475
+ let string = data.toString();
476
+ let rule = /https?:\/\/.[^"]+\.(png|jpg|gif|jpeg)/gi;
477
+ let ary = string.match(rule); //拿到所有jpg结尾的链接集合
481
478
  if (callback) callback(ary);
482
- var x = 0;
483
- for (var i in ary) {
479
+ let x = 0;
480
+ for (let i in ary) {
484
481
  M.download(ary[i], file + (x++) + ary[i].substr(ary[i].lastIndexOf(".")));
485
482
  }
486
483
  });
@@ -599,8 +596,8 @@ M.mkdir = function (dirpath, dirname) {
599
596
  M.copyDir = function (src, dst) {
600
597
  let paths = fs.readdirSync(src); //同步读取当前目录
601
598
  paths.forEach(function (path) {
602
- var _src = src + '/' + path;
603
- var _dst = dst + '/' + path;
599
+ let _src = src + '/' + path;
600
+ let _dst = dst + '/' + path;
604
601
  fs.stat(_src, function (err, stats) { //stats 该对象 包含文件属性
605
602
  if (err) throw err;
606
603
  if (stats.isFile()) { //如果是个文件则拷贝
@@ -643,7 +640,7 @@ M.appendFile = function (file, str) {
643
640
  */
644
641
  M.getObjByFile = function (file) {
645
642
  data = M.readFile(file) || "[]"
646
- var obj = JSON.parse(data.toString());
643
+ let obj = JSON.parse(data.toString());
647
644
  return obj;
648
645
  }
649
646
  M.writeObjToFile = function (file, obj) {
@@ -652,7 +649,7 @@ M.writeObjToFile = function (file, obj) {
652
649
 
653
650
  M.addObjToFile = function (file, obj) {
654
651
  try {
655
- var d = M.getObjByFile(file);
652
+ let d = M.getObjByFile(file);
656
653
  M.writeObjToFile(file, [...d, obj]);
657
654
  } catch (e) {
658
655
  M.writeObjToFile(file, [obj]);
@@ -665,8 +662,8 @@ M.deleteObjByIdFile = function (file, id) {
665
662
  } else {
666
663
  ids = id;
667
664
  }
668
- var d = M.getObjByFile(file);
669
- var d1 = M.getObjByFile(file);
665
+ let d = M.getObjByFile(file);
666
+ let d1 = M.getObjByFile(file);
670
667
  let d_num = 0;
671
668
  for (let i = 0; i < d1.length; i++) {
672
669
  if (ids.indexOf(d1[i].id) >= 0) {
@@ -681,8 +678,8 @@ M.deleteObjByIdFile = function (file, id) {
681
678
  M.deleteObjByPropFile = function (file, o) {
682
679
  let o_key = Object.keys(o)[0];
683
680
  let o_val = o[o_key]
684
- var d = M.getObjByFile(file);
685
- var d1 = M.getObjByFile(file);
681
+ let d = M.getObjByFile(file);
682
+ let d1 = M.getObjByFile(file);
686
683
  let d_num = 0;
687
684
  for (let i = 0; i < d1.length; i++) {
688
685
  if (d1[i][o_key] == o_val) {
@@ -695,7 +692,7 @@ M.deleteObjByPropFile = function (file, o) {
695
692
  }
696
693
 
697
694
  M.updateObjByIdFile = function (file, obj) {
698
- var d = M.getObjByFile(file);
695
+ let d = M.getObjByFile(file);
699
696
  for (let i = 0; i < d.length; i++) {
700
697
  if (d[i].id == obj.id) {
701
698
  d.splice(i, 1, Object.assign(d[i],obj));
@@ -705,7 +702,7 @@ M.updateObjByIdFile = function (file, obj) {
705
702
  M.writeObjToFile(file, d);
706
703
  }
707
704
  M.getObjByIdFile = function (file, id) {
708
- var d = M.getObjByFile(file);
705
+ let d = M.getObjByFile(file);
709
706
  for (let i = 0; i < d.length; i++) {
710
707
  if (d[i].id == id) {
711
708
  return d[i];
@@ -713,7 +710,7 @@ M.getObjByIdFile = function (file, id) {
713
710
  }
714
711
  }
715
712
  M.listAllObjByPropFile = function (file, caseObj) {
716
- var d = M.getObjByFile(file);
713
+ let d = M.getObjByFile(file);
717
714
  let o_keys = Object.keys(caseObj);
718
715
  if (caseObj && o_keys.length>0) {
719
716
  let r_list = [];
@@ -814,13 +811,14 @@ M.getAttribute = function (k) {
814
811
  M.readLine =async function (file, callback) {
815
812
  let lineCount=0;
816
813
  return new Promise((resolve, reject) =>{
817
- var remaining = '';
818
- var input = fs.createReadStream(file);
814
+ let remaining = '';
815
+ let input = fs.createReadStream(file);
816
+ input.setEncoding('utf-8');
819
817
  input.on('data', function (data) {
820
818
  remaining += data;
821
- var index = remaining.indexOf('\n');
819
+ let index = remaining.indexOf('\n');
822
820
  while (index > -1) {
823
- var line = remaining.substring(0, index);
821
+ let line = remaining.substring(0, index);
824
822
  remaining = remaining.substring(index + 1);
825
823
  lineCount++;
826
824
  callback(line);
@@ -836,8 +834,33 @@ M.readLine =async function (file, callback) {
836
834
 
837
835
 
838
836
  M.readCsvLine =async function (file, callback) {
837
+ function parseStringToArray(str) {
838
+ const result = [];
839
+ let temp = '';
840
+ let inQuotes = false;
841
+ for (let i = 0; i < str.length; i++) {
842
+ const char = str[i];
843
+ if (char === ',' && !inQuotes) {
844
+ result.push(temp.trim());
845
+ temp = '';
846
+ } else if (char === '"') {
847
+ if (inQuotes && str[i + 1] === '"') {
848
+ temp += '"';
849
+ i++;
850
+ } else {
851
+ inQuotes = !inQuotes;
852
+ }
853
+ } else {
854
+ temp += char;
855
+ }
856
+ }
857
+
858
+ result.push(temp.trim());
859
+
860
+ return result;
861
+ }
839
862
  return M.readLine(file, function (line) {
840
- callback(line.replace("\r", "").split(/(?<!\"[^,]+),(?![^,]+\")/));
863
+ callback(parseStringToArray(line));
841
864
  })
842
865
  }
843
866
 
@@ -855,7 +878,7 @@ M.getFileList = function (path) {
855
878
  function walk(file) {
856
879
  states = fs.statSync(path + '/' + file);
857
880
  if (states.isDirectory()) {
858
- var item;
881
+ let item;
859
882
  if (targetObj["children"]) {
860
883
  item = {name: file, children: [], value: path + '/' + file};
861
884
  targetObj["children"].push(item);
@@ -867,24 +890,24 @@ M.getFileList = function (path) {
867
890
  readFile(path + '/' + file, filesList, item);
868
891
  } else {
869
892
  //创建一个对象保存信息
870
- var obj = new Object();
893
+ let obj = new Object();
871
894
  obj.size = states.size;//文件大小,以字节为单位
872
895
  obj.name = file;//文件名
873
896
  obj.path = path + '/' + file; //文件绝对路径
874
897
 
875
898
  if (targetObj["children"]) {
876
- var item = {name: file, value: obj.path}
899
+ let item = {name: file, value: obj.path}
877
900
  targetObj["children"].push(item);
878
901
  } else {
879
- var item = {name: file, value: obj.path};
902
+ let item = {name: file, value: obj.path};
880
903
  filesList.push(item);
881
904
  }
882
905
  }
883
906
  }
884
907
  }
885
908
 
886
- var filesList = [];
887
- var targetObj = {};
909
+ let filesList = [];
910
+ let targetObj = {};
888
911
  readFile(path, filesList, targetObj);
889
912
  return filesList;
890
913
  }
@@ -897,7 +920,7 @@ M.getFileDirList = function (path) {
897
920
  function walk(file) {
898
921
  states = fs.statSync(path + '/' + file);
899
922
  if (states.isDirectory()) {
900
- var item;
923
+ let item;
901
924
  let dir=path + '/' + file;
902
925
  if(dir.indexOf("lib")==-1){
903
926
  dirList.push(path + '/' + file)
@@ -913,9 +936,9 @@ M.getFileDirList = function (path) {
913
936
  }
914
937
  }
915
938
  }
916
- var dirList=[]
917
- var filesList = [];
918
- var targetObj = {};
939
+ let dirList=[]
940
+ let filesList = [];
941
+ let targetObj = {};
919
942
  readFile(path, filesList, targetObj);
920
943
  return dirList;
921
944
  }
@@ -967,10 +990,10 @@ M.getSqlite = function (dbName) {
967
990
  if (M.sqlite) {
968
991
  return M.sqlite;
969
992
  }
970
- var SQLite3 = require('sqlite3').verbose();
971
- var Db = new SQLite3.Database(dbName || "ming_autotest.db");
993
+ let SQLite3 = require('sqlite3').verbose();
994
+ let Db = new SQLite3.Database(dbName || "ming_autotest.db");
972
995
  Db.doSql = function doSql(sql) {
973
- var promise = new Promise(function (reslove, reject) {
996
+ let promise = new Promise(function (reslove, reject) {
974
997
  if (Db.display_sql_enable) {
975
998
  M.log(sql)
976
999
  }
@@ -1008,7 +1031,7 @@ M.getMySql = function (dbConfig) {
1008
1031
  if (M.mysql) {
1009
1032
  return M.mysql;
1010
1033
  }
1011
- var mysql = require('mysql');
1034
+ let mysql = require('mysql');
1012
1035
  let defaultDbConfig = {
1013
1036
  "host": dbConfig.host || "localhost",
1014
1037
  "user": dbConfig.user || "root",
@@ -1019,10 +1042,10 @@ M.getMySql = function (dbConfig) {
1019
1042
  dateStrings: true,
1020
1043
  timezone: "08:00"
1021
1044
  }
1022
- var Db = {};
1045
+ let Db = {};
1023
1046
  Db.dbConfig=defaultDbConfig;
1024
1047
  console.log("connect mysql", defaultDbConfig)
1025
- var pool = mysql.createPool(defaultDbConfig);
1048
+ let pool = mysql.createPool(defaultDbConfig);
1026
1049
  Db.pool=pool;
1027
1050
  Db.getConnection= function(callback){
1028
1051
  return new Promise(((resolve, reject) => {
@@ -1039,7 +1062,7 @@ M.getMySql = function (dbConfig) {
1039
1062
  if (Db.display_sql_enable) {
1040
1063
  M.log(sql)
1041
1064
  }
1042
- var promise = new Promise(function (reslove, reject) {
1065
+ let promise = new Promise(function (reslove, reject) {
1043
1066
  pool.getConnection(function (err, connection) {
1044
1067
  connection.query(sql, params, function (err, rows) {
1045
1068
  if (err) {
@@ -1062,7 +1085,7 @@ M.getMySql = function (dbConfig) {
1062
1085
  if (Db.display_sql_enable) {
1063
1086
  M.log(sql)
1064
1087
  }
1065
- var promise = new Promise(function (reslove, reject) {
1088
+ let promise = new Promise(function (reslove, reject) {
1066
1089
  connection.query(sql, params, function (err, rows) {
1067
1090
  if (err) {
1068
1091
  reject(err);
@@ -1111,11 +1134,11 @@ M.getMongoDB = function (dbConfig) {
1111
1134
  if (M.mongoDb) {
1112
1135
  return M.mongoDb;
1113
1136
  }
1114
- var MongoDB=require('mongodb');
1115
- var MongoClient =MongoDB.MongoClient;
1137
+ let MongoDB=require('mongodb');
1138
+ let MongoClient =MongoDB.MongoClient;
1116
1139
  const ObjectID = MongoDB.ObjectID;
1117
1140
 
1118
- var Config={
1141
+ let Config={
1119
1142
  dbUrl: dbConfig.dbUrl|| 'mongodb://localhost:27017/',
1120
1143
  dbName: dbConfig.dbName|| 'miapi'
1121
1144
  };
@@ -1146,7 +1169,7 @@ M.getMongoDB = function (dbConfig) {
1146
1169
  }
1147
1170
  return new Promise((resolve,reject)=>{
1148
1171
  MingMongoClient.connect().then((db)=>{
1149
- var result=db.collection(collectionName).find(json);
1172
+ let result=db.collection(collectionName).find(json);
1150
1173
  result.toArray(function(err,docs){
1151
1174
  if(err){
1152
1175
  reject(err);
@@ -1242,7 +1265,7 @@ M.getMongoDB = function (dbConfig) {
1242
1265
  }
1243
1266
  return new Promise((resolve,reject)=>{
1244
1267
  MingMongoClient.connect().then((db)=>{
1245
- var whereArgs = {
1268
+ let whereArgs = {
1246
1269
  _id: new ObjectID(id)
1247
1270
  };
1248
1271
  db.collection(collectionName).findOne(whereArgs,{},function(err,result){
@@ -1271,8 +1294,8 @@ M.getMongoDB = function (dbConfig) {
1271
1294
  * ----------------------Sql CRUD START-------------------------------------------
1272
1295
  */
1273
1296
  M.getInsertObjSql = function (tableName, obj) {
1274
- var fields = "(";
1275
- var values = "(";
1297
+ let fields = "(";
1298
+ let values = "(";
1276
1299
  for (let field in obj) {
1277
1300
  fields += field + ",";
1278
1301
  values += `'${obj[field]}'` + ",";
@@ -1286,7 +1309,7 @@ M.getInsertObjSql = function (tableName, obj) {
1286
1309
  }
1287
1310
 
1288
1311
  M.getDeleteObjSql = function (tableName, obj) {
1289
- var fields = [];
1312
+ let fields = [];
1290
1313
  for (let field in obj) {
1291
1314
  fields.push(field);
1292
1315
  }
@@ -1296,7 +1319,7 @@ M.getDeleteObjSql = function (tableName, obj) {
1296
1319
  }
1297
1320
 
1298
1321
  M.getUpdateObjSql = function (tableName, obj, caseObj) {
1299
- var fields = [];
1322
+ let fields = [];
1300
1323
  for (let field in obj) {
1301
1324
  if (field != "id")
1302
1325
  fields.push(field);
@@ -1305,7 +1328,7 @@ M.getUpdateObjSql = function (tableName, obj, caseObj) {
1305
1328
  if (!caseObj) {
1306
1329
  sql = `update ${tableName} set ${fields.map(u => u + "='" + obj[u] + "'")} where id=${obj.id}`;
1307
1330
  } else {
1308
- var caseObjfields = [];
1331
+ let caseObjfields = [];
1309
1332
  for (let caseObjfield in caseObj) {
1310
1333
  caseObjfields.push(caseObjfield)
1311
1334
  }
@@ -1317,7 +1340,7 @@ M.getUpdateObjSql = function (tableName, obj, caseObj) {
1317
1340
 
1318
1341
 
1319
1342
  M.getSelectObjSql = function (tableName, obj) {
1320
- var fields = [];
1343
+ let fields = [];
1321
1344
  for (let field in obj) {
1322
1345
  fields.push(field);
1323
1346
  }
@@ -1343,7 +1366,7 @@ M.getSelectObjSql = function (tableName, obj) {
1343
1366
  *封装返回数据
1344
1367
  */
1345
1368
  M.result = function (data, success,message) {
1346
- var r = {};
1369
+ let r = {};
1347
1370
  if (success == false) {
1348
1371
  r.code = -2;
1349
1372
  r.msg = message||"操作失败";
@@ -1353,7 +1376,7 @@ M.result = function (data, success,message) {
1353
1376
  }
1354
1377
  r.requestId=M.req? M.req.requestId:"";
1355
1378
  try {
1356
- var obj = JSON.parse(data);
1379
+ let obj = JSON.parse(data);
1357
1380
  if (typeof obj == 'object' && obj) {
1358
1381
  r.data = obj;
1359
1382
  } else {
@@ -1386,7 +1409,7 @@ M.failResult=(msg,code,d)=>{
1386
1409
  *获取下划线式的对象
1387
1410
  */
1388
1411
  M.getUnderlineObj = function (obj) {
1389
- var result = {};
1412
+ let result = {};
1390
1413
  for (let field in obj) {
1391
1414
  result[field.humpToUnderline()] = obj[field]
1392
1415
  }
@@ -1397,7 +1420,7 @@ M.getUnderlineObj = function (obj) {
1397
1420
  *获取驼峰式的对象
1398
1421
  */
1399
1422
  M.getHumpObj = function (obj) {
1400
- var result = {};
1423
+ let result = {};
1401
1424
  for (let field in obj) {
1402
1425
  result[field.underlineToHump()] = obj[field]
1403
1426
  }
@@ -1410,14 +1433,14 @@ M.randomStr = function () {
1410
1433
 
1411
1434
  M.urlStringify = function (obj) {
1412
1435
  if (obj !== null && typeof obj === 'object') {
1413
- var keys = Object.keys(obj);
1414
- var len = keys.length;
1415
- var flast = len - 1;
1416
- var fields = '';
1417
- for (var i = 0; i < len; ++i) {
1418
- var k = keys[i];
1419
- var v = obj[k];
1420
- var ks = k + "=";
1436
+ let keys = Object.keys(obj);
1437
+ let len = keys.length;
1438
+ let flast = len - 1;
1439
+ let fields = '';
1440
+ for (let i = 0; i < len; ++i) {
1441
+ let k = keys[i];
1442
+ let v = obj[k];
1443
+ let ks = k + "=";
1421
1444
  fields += ks + v;
1422
1445
  if (i < flast)
1423
1446
  fields += "&";
@@ -1429,12 +1452,12 @@ M.urlStringify = function (obj) {
1429
1452
 
1430
1453
  M.urlParse = function (url) {
1431
1454
  url = url.substr(url.indexOf("?") + 1);
1432
- var t, n, r, i = url, s = {};
1455
+ let t, n, r, i = url, s = {};
1433
1456
  t = i.split("&"),
1434
1457
  r = null,
1435
1458
  n = null;
1436
- for (var o in t) {
1437
- var u = t[o].indexOf("=");
1459
+ for (let o in t) {
1460
+ let u = t[o].indexOf("=");
1438
1461
  u !== -1 && (r = t[o].substr(0, u),
1439
1462
  n = t[o].substr(u + 1),
1440
1463
  s[r] = n)
@@ -1457,7 +1480,7 @@ M.err = function (e) {
1457
1480
 
1458
1481
 
1459
1482
  M.server = function () {
1460
- var G = this; /*全局变量,也就是M*/
1483
+ let G = this; /*全局变量,也就是M*/
1461
1484
  //静态资源路径
1462
1485
  this._views = "static";
1463
1486
  //key为去除rest参数的url,val为原始url
@@ -1479,8 +1502,9 @@ M.server = function () {
1479
1502
  //如果实现此函数,则只能有一个此服务
1480
1503
  this._server = function () {
1481
1504
  };
1482
- var app =async function (req, res) {
1505
+ let app =async function (req, res) {
1483
1506
  try {
1507
+ req.setEncoding('utf-8');
1484
1508
  M.req=req;
1485
1509
  M.res=res;
1486
1510
  //是否已经发送过了
@@ -1497,7 +1521,7 @@ M.server = function () {
1497
1521
  //是否为rest请求
1498
1522
  req.isRestRequest = function () {
1499
1523
  if (Object.keys(G._rest).length == 0) return false;
1500
- var isRest = false;
1524
+ let isRest = false;
1501
1525
  for (let i = 0; i < Object.keys(G._rest).length; i++) {
1502
1526
  if (pathname.startsWith(Object.keys(G._rest)[i])) {
1503
1527
  isRest = true;
@@ -1579,9 +1603,9 @@ M.server = function () {
1579
1603
  if (!isString) {
1580
1604
  text = JSON.stringify(text);
1581
1605
  }
1582
- var pathname = url_module.parse(url).pathname; /*获取url的值*/
1606
+ let pathname = url_module.parse(url).pathname; /*获取url的值*/
1583
1607
  //获取文件的后缀名
1584
- var extname = path.extname(pathname);
1608
+ let extname = path.extname(pathname);
1585
1609
  res.writeHead(200, {"Content-Type": "" + (privateObj.staticMime[extname] || 'text/html') + ";charset='utf-8'",});
1586
1610
  res.write(text);
1587
1611
  res.end();
@@ -1608,7 +1632,7 @@ M.server = function () {
1608
1632
  throw e;
1609
1633
  }).pipe(res);
1610
1634
  }else {
1611
- var func = http;
1635
+ let func = http;
1612
1636
  if (url.indexOf("https") >= 0) {
1613
1637
  func = https;
1614
1638
  }
@@ -1647,9 +1671,9 @@ M.server = function () {
1647
1671
  if (!isString) {
1648
1672
  text = JSON.stringify(text);
1649
1673
  }
1650
- var pathname = url_module.parse(url).pathname; /*获取url的值*/
1674
+ let pathname = url_module.parse(url).pathname; /*获取url的值*/
1651
1675
  //获取文件的后缀名
1652
- var extname = path.extname(pathname);
1676
+ let extname = path.extname(pathname);
1653
1677
  res.writeHead(200, {"Content-Type": "" + (privateObj.staticMime[extname] || 'text/html') + ";charset='utf-8'",});
1654
1678
  let templateStr=""
1655
1679
  try {
@@ -1694,13 +1718,13 @@ M.server = function () {
1694
1718
  res.end();
1695
1719
  }
1696
1720
  //获取路由
1697
- var pathname = url_module.parse(req.url).pathname;
1721
+ let pathname = url_module.parse(req.url).pathname;
1698
1722
  if (!pathname.endsWith('/')) {
1699
1723
  pathname = pathname + '/';
1700
1724
  }
1701
1725
  // pathname.startsWith("/usr/")
1702
1726
  //获取请求的方式 get post
1703
- var method = req.method.toLowerCase();
1727
+ let method = req.method.toLowerCase();
1704
1728
  if (req.isStaticRequest()) {
1705
1729
 
1706
1730
  await G._begin(req, res);
@@ -1710,7 +1734,7 @@ M.server = function () {
1710
1734
 
1711
1735
  //为req加个params用于存放请求参数
1712
1736
  req.params = {};
1713
- var mapingPath = "";
1737
+ let mapingPath = "";
1714
1738
  //如果是rest风格的请求,为其封装请求参数
1715
1739
  if (req.isRestRequest()) {
1716
1740
  for (let i = 0; i < Object.keys(G._rest).length; i++) {
@@ -1719,7 +1743,7 @@ M.server = function () {
1719
1743
  mapingPath = G._rest[pathname];
1720
1744
  }
1721
1745
  }
1722
- var realPathName = url_module.parse(req.url).pathname;
1746
+ let realPathName = url_module.parse(req.url).pathname;
1723
1747
  if (!realPathName.endsWith('/')) {
1724
1748
  realPathName = realPathName + '/';
1725
1749
  }
@@ -1742,7 +1766,7 @@ M.server = function () {
1742
1766
  method == "delete"
1743
1767
  ) && (G['_' + method][pathname])) {
1744
1768
  if (method != 'get') { /*执行post请求*/
1745
- var postStr = '';
1769
+ let postStr = '';
1746
1770
  req.on('data', function (chunk) {
1747
1771
  postStr += chunk;
1748
1772
  })
@@ -1859,7 +1883,7 @@ M.server = function () {
1859
1883
  app.get = function (url, callback) {
1860
1884
  const single=(url,callback)=>{
1861
1885
  url = M.formatUrl(url);
1862
- var realUrl = url;
1886
+ let realUrl = url;
1863
1887
  if (url.indexOf(":") > 0) {
1864
1888
  url = url.substr(0, url.indexOf(":"));
1865
1889
  G._rest[url] = realUrl;
@@ -1874,7 +1898,7 @@ M.server = function () {
1874
1898
  app.post = function (url, callback) {
1875
1899
  const single=(url,callback)=>{
1876
1900
  url = M.formatUrl(url);
1877
- var realUrl = url;
1901
+ let realUrl = url;
1878
1902
  if (url.indexOf(":") > 0) {
1879
1903
  url = url.substr(0, url.indexOf(":"));
1880
1904
  G._rest[url] = realUrl;
@@ -1887,7 +1911,7 @@ M.server = function () {
1887
1911
  app.put = function (url, callback) {
1888
1912
  const single=(url,callback)=>{
1889
1913
  url = M.formatUrl(url);
1890
- var realUrl = url;
1914
+ let realUrl = url;
1891
1915
  if (url.indexOf(":") > 0) {
1892
1916
  url = url.substr(0, url.indexOf(":"));
1893
1917
  G._rest[url] = realUrl;
@@ -1900,7 +1924,7 @@ M.server = function () {
1900
1924
  app.delete = function (url, callback) {
1901
1925
  const single=(url,callback)=>{
1902
1926
  url = M.formatUrl(url);
1903
- var realUrl = url;
1927
+ let realUrl = url;
1904
1928
  if (url.indexOf(":") > 0) {
1905
1929
  url = url.substr(0, url.indexOf(":"));
1906
1930
  G._rest[url] = realUrl;
@@ -1915,7 +1939,7 @@ M.server = function () {
1915
1939
  app.mapping = function (url, callback) {
1916
1940
  const single=(url,callback)=>{
1917
1941
  url = M.formatUrl(url);
1918
- var realUrl = url;
1942
+ let realUrl = url;
1919
1943
  if (url.indexOf(":") > 0) {
1920
1944
  url = url.substr(0, url.indexOf(":"));
1921
1945
  G._rest[url] = realUrl;
@@ -2029,6 +2053,7 @@ M.getAxiosConfig = async (req) => {
2029
2053
  axiosConfig.method = req.method.toLocaleLowerCase();
2030
2054
  axiosConfig.headers = req.headers
2031
2055
  let postStr = '';
2056
+ req.setEncoding('utf-8');
2032
2057
  req.on('data', function (chunk) {
2033
2058
  postStr += chunk;
2034
2059
  })
@@ -2052,8 +2077,8 @@ M.getAxiosConfig = async (req) => {
2052
2077
 
2053
2078
  M.axios = function (axiosConfig) {
2054
2079
  axiosConfig.headers.host = "";
2055
- var urlObj = url_module.parse(axiosConfig.url)
2056
- var options = {
2080
+ let urlObj = url_module.parse(axiosConfig.url)
2081
+ let options = {
2057
2082
  hostname: urlObj.hostname,
2058
2083
  port: urlObj.port,
2059
2084
  path: urlObj.path,
@@ -2064,9 +2089,9 @@ M.axios = function (axiosConfig) {
2064
2089
  if (axiosConfig.url.startsWith("https")) {
2065
2090
  reqHttp = https;
2066
2091
  }
2067
- var html = '';
2092
+ let html = '';
2068
2093
  return new Promise((resolve, reject) => {
2069
- var req = reqHttp.request(options, function (res) {
2094
+ let req = reqHttp.request(options, function (res) {
2070
2095
  options = M.httpBefore(options);
2071
2096
  if (options == false) {
2072
2097
  return;
@@ -2082,8 +2107,7 @@ M.axios = function (axiosConfig) {
2082
2107
 
2083
2108
  });
2084
2109
  req.on('error', function (err) {
2085
- console.error(err);
2086
- throw err;
2110
+ reject(err);
2087
2111
  });
2088
2112
  req.write(axiosConfig.body);
2089
2113
  req.end();
@@ -2108,13 +2132,13 @@ privateObj.dealUseServer = async function (req, res) {
2108
2132
 
2109
2133
  privateObj.staticServer = async function (req, res, staticPath) {
2110
2134
  if (res.alreadySend) return;
2111
- var pathname = url_module.parse(req.url).pathname; /*获取url的值*/
2135
+ let pathname = url_module.parse(req.url).pathname; /*获取url的值*/
2112
2136
  if (pathname == '/') {
2113
2137
  pathname = '/index.html'; /*默认加载的首页*/
2114
2138
  }
2115
2139
  let fileName = pathname.replace("/", "");
2116
2140
  //获取文件的后缀名
2117
- var extname = path.extname(pathname);
2141
+ let extname = path.extname(pathname);
2118
2142
 
2119
2143
  if (fileName.startsWith("__default_")) {
2120
2144
  res.setHeader("Access-Control-Allow-Origin", "*");
@@ -2265,7 +2289,7 @@ M.sseServer = function () {
2265
2289
  * ----------------------其他工具函数START--------------------------------------------
2266
2290
  */
2267
2291
  M.exec = function (comand) {
2268
- var promise = new Promise(function (reslove, reject) {
2292
+ let promise = new Promise(function (reslove, reject) {
2269
2293
  child_process.exec(comand, function (err, stdout, stderr) {
2270
2294
  if (err || stderr) console.error(err, stderr);
2271
2295
  reslove(stdout);
@@ -2276,11 +2300,11 @@ M.exec = function (comand) {
2276
2300
  }
2277
2301
 
2278
2302
  M.getMyIp = function () {
2279
- var interfaces = require('os').networkInterfaces();
2280
- for (var devName in interfaces) {
2281
- var iface = interfaces[devName];
2282
- for (var i = 0; i < iface.length; i++) {
2283
- var alias = iface[i];
2303
+ let interfaces = require('os').networkInterfaces();
2304
+ for (let devName in interfaces) {
2305
+ let iface = interfaces[devName];
2306
+ for (let i = 0; i < iface.length; i++) {
2307
+ let alias = iface[i];
2284
2308
  if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
2285
2309
  return alias.address;
2286
2310
  }
@@ -2299,8 +2323,8 @@ M.getMyIp = function () {
2299
2323
  */
2300
2324
 
2301
2325
  M.sleep = function (numberMillis) {
2302
- var now = new Date();
2303
- var exitTime = now.getTime() + numberMillis;
2326
+ let now = new Date();
2327
+ let exitTime = now.getTime() + numberMillis;
2304
2328
  while (true) {
2305
2329
  now = new Date();
2306
2330
  if (now.getTime() > exitTime)
@@ -2436,6 +2460,7 @@ privateObj.staticMime = {
2436
2460
  ".hdml": "text/x-hdml",
2437
2461
  ".hlp": "application/winhlp",
2438
2462
  ".hqx": "application/mac-binhex40",
2463
+ ".hex": "text/html",
2439
2464
  ".hta": "application/hta",
2440
2465
  ".htc": "text/x-component",
2441
2466
  ".htm": "text/html",
@@ -2651,7 +2676,6 @@ privateObj.staticMime = {
2651
2676
  ".setreg": "application/set-registration-initiation",
2652
2677
  ".sgm": "text/x-sgml",
2653
2678
  ".sgml": "text/x-sgml",
2654
- ".sh": "application/x-sh",
2655
2679
  ".shar": "application/x-shar",
2656
2680
  ".shtml": "magnus-internal/parsed-html",
2657
2681
  ".shw": "application/presentations",
@@ -2793,7 +2817,6 @@ privateObj.staticMime = {
2793
2817
  ".xlt": "application/vnd.ms-excel",
2794
2818
  ".xlw": "application/vnd.ms-excel",
2795
2819
  ".xm": "audio/x-mod",
2796
- ".xml": "text/plain",
2797
2820
  ".xml": "application/xml",
2798
2821
  ".xmz": "audio/x-mod",
2799
2822
  ".xof": "x-world/x-vrml",
@@ -2833,8 +2856,8 @@ privateObj.staticMime = {
2833
2856
  ".perl": "text/plain",
2834
2857
  ".php": "text/plain",
2835
2858
  ".py": "text/plain",
2859
+ ".json5": "text/plain",
2836
2860
  ".redis": "text/plain",
2837
- ".conf": "text/conf",
2838
2861
  ".sql": "text/sql",
2839
2862
  ".ejs": "text/plain"
2840
2863
  }
@@ -2863,7 +2886,7 @@ M.init = function () {
2863
2886
  * 下划线命名转为驼峰命名
2864
2887
  */
2865
2888
  String.prototype.underlineToHump = function () {
2866
- var re = /_(\w)/g;
2889
+ let re = /_(\w)/g;
2867
2890
  str = this.replace(re, function ($0, $1) {
2868
2891
  return $1.toUpperCase();
2869
2892
  });
@@ -2874,7 +2897,7 @@ M.init = function () {
2874
2897
  * 驼峰命名转下划线
2875
2898
  */
2876
2899
  String.prototype.humpToUnderline = function () {
2877
- var re = /_(\w)/g;
2900
+ let re = /_(\w)/g;
2878
2901
  str = this.replace(/([A-Z])/g, "_$1").toLowerCase();
2879
2902
  return str;
2880
2903
  }
@@ -2893,7 +2916,7 @@ M.init = function () {
2893
2916
  }
2894
2917
  //格式化日期
2895
2918
  Date.prototype.format = function (fmt) {
2896
- var o = {
2919
+ let o = {
2897
2920
  "M+": this.getMonth() + 1, //月份
2898
2921
  "d+": this.getDate(), //日
2899
2922
  "h+": this.getHours(), //小时
@@ -2905,7 +2928,7 @@ M.init = function () {
2905
2928
  if (/(y+)/.test(fmt)) {
2906
2929
  fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
2907
2930
  }
2908
- for (var k in o) {
2931
+ for (let k in o) {
2909
2932
  if (new RegExp("(" + k + ")").test(fmt)) {
2910
2933
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
2911
2934
  }
@@ -57,12 +57,12 @@ class TcpServer {
57
57
 
58
58
  // 客户端连接关闭
59
59
  client.on('close', function (err) {
60
- delete that.socketClientMap[endPoint];
60
+ delete TcpServer.socketClientMap[endPoint];
61
61
  TcpServer._EventCallBack["close"]?TcpServer._EventCallBack["close"](client):"";
62
62
  });
63
63
  // 客户端连接错误
64
64
  client.on('error', function (err) {
65
- delete that.socketClientMap[endPoint];
65
+ delete TcpServer.socketClientMap[endPoint];
66
66
  TcpServer._EventCallBack["error"]?TcpServer._EventCallBack["error"](client):"";
67
67
  });
68
68
  });
@@ -85,20 +85,20 @@ class TcpServer {
85
85
  //设置关闭时的回调函数
86
86
  this.socketServer.on('close', function () {
87
87
  console.log('sever closed');
88
- that.socketClientMap={};
88
+ TcpServer.socketClientMap={};
89
89
  });
90
90
 
91
91
  //设置出错时的回调函数
92
92
  this.socketServer.on('error', function () {
93
93
  console.log('sever error');
94
- that.socketClientMap={};
94
+ TcpServer.socketClientMap={};
95
95
  });
96
96
  }
97
97
 
98
98
  send(buffer){
99
- let clientEndPointList= Object.keys(this.socketClientMap);
99
+ let clientEndPointList= Object.keys(TcpServer.socketClientMap);
100
100
  for (let i=0;i<clientEndPointList.length;i++){
101
- this.socketClientMap[clientEndPointList[i]].write(buffer)
101
+ TcpServer.socketClientMap[clientEndPointList[i]].write(buffer)
102
102
  }
103
103
 
104
104
  }
@@ -0,0 +1,109 @@
1
+ import net from "net"
2
+ import os from 'os'
3
+
4
+ class TcpServer {
5
+ static _EventCallBack={};
6
+ static socketClientMap={};
7
+ set(url, callback) {
8
+ TcpServer._EventCallBack[url]=callback;
9
+ }
10
+ constructor() {
11
+ this.localAddress=this.getIpAddress();
12
+ }
13
+ getIpAddress(){
14
+ /**os.networkInterfaces() 返回一个对象,该对象包含已分配了网络地址的网络接口 */
15
+ var interfaces = os.networkInterfaces();
16
+ for (var devName in interfaces) {
17
+ var iface = interfaces[devName];
18
+ for (var i = 0; i < iface.length; i++) {
19
+ var alias = iface[i];
20
+ if (
21
+ alias.family === "IPv4" &&
22
+ alias.address !== "127.0.0.1" &&
23
+ !alias.internal
24
+ ) {
25
+ return alias.address;
26
+ }
27
+ }
28
+ }
29
+ }
30
+
31
+
32
+ listen(port){
33
+ let that=this;
34
+ this.localPort=port;
35
+ this.socketServer = net.createServer(function (client) {
36
+ let endPoint= client.remoteAddress+":"+client.remotePort;
37
+ TcpServer.socketClientMap[endPoint]=client;
38
+ let req={};
39
+ req.remoteIp=client.remoteAddress;
40
+ req.remotePort=client.remotePort;
41
+ TcpServer._EventCallBack['connect']? TcpServer._EventCallBack['connect'](req,null): console.log(endPoint+"connected");
42
+
43
+ // 接收客户端的数据
44
+ client.on('data', function (data) {
45
+ let req={};
46
+ req.remoteIp=client.remoteAddress;
47
+ req.remotePort=client.remotePort;
48
+ req.params=data;
49
+ let res={};
50
+ res.send=function (v){
51
+ if(Array.isArray(v)){
52
+ v=new Buffer(v)
53
+ }
54
+ client.write(v)
55
+ }
56
+ TcpServer._EventCallBack['data'](req,res);
57
+ });
58
+
59
+ // 客户端连接关闭
60
+ client.on('close', function (err) {
61
+ delete TcpServer.socketClientMap[endPoint];
62
+ TcpServer._EventCallBack["close"]?TcpServer._EventCallBack["close"](client):"";
63
+ });
64
+ // 客户端连接错误
65
+ client.on('error', function (err) {
66
+ delete TcpServer.socketClientMap[endPoint];
67
+ TcpServer._EventCallBack["error"]?TcpServer._EventCallBack["error"](client):"";
68
+ });
69
+ });
70
+ this.socketServer.listen(
71
+ {
72
+ port: port,
73
+ host: '0.0.0.0',
74
+ },
75
+ function () {
76
+ //console.log('Tcpserver listen listen on '+that.localPort);
77
+ }
78
+ );
79
+
80
+ //设置监听时的回调函数
81
+ this.socketServer.on('listening', function () {
82
+ const { address, port } = that.socketServer.address();
83
+ console.log('Tcpserver listen on '+port);
84
+ });
85
+
86
+ //设置关闭时的回调函数
87
+ this.socketServer.on('close', function () {
88
+ console.log('sever closed');
89
+ TcpServer.socketClientMap={};
90
+ });
91
+
92
+ //设置出错时的回调函数
93
+ this.socketServer.on('error', function () {
94
+ console.log('sever error');
95
+ TcpServer.socketClientMap={};
96
+ });
97
+ }
98
+
99
+ send(buffer){
100
+ let clientEndPointList= Object.keys(TcpServer.socketClientMap);
101
+ for (let i=0;i<clientEndPointList.length;i++){
102
+ TcpServer.socketClientMap[clientEndPointList[i]].write(buffer)
103
+ }
104
+
105
+ }
106
+
107
+ }
108
+
109
+ export default TcpServer;
package/package.json CHANGED
@@ -46,5 +46,5 @@
46
46
  "scripts": {
47
47
  "test": "echo \"Error: no test specified\" && exit 1"
48
48
  },
49
- "version": "3.0.1"
49
+ "version": "3.0.3"
50
50
  }