ming_node 3.0.1 → 3.0.2

Sign up to get free protection for your applications and to get access to all the features.
@@ -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)
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.2
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) {
@@ -206,10 +206,10 @@ M._request = function (url, callback, data, headers,methed) {
206
206
  }
207
207
 
208
208
  url = privateObj.appendDataToUrl(url, M.reqComQueryparams);
209
- var html = '';
210
- var urlObj = url_module.parse(url)
209
+ let html = '';
210
+ let urlObj = url_module.parse(url)
211
211
  //发送 http Post 请求
212
- var postData = querystring.stringify(data);
212
+ let postData = querystring.stringify(data);
213
213
  if( headers["Content-Type"]==undefined){
214
214
  headers["Content-Type"] ="application/json";
215
215
  }
@@ -225,7 +225,7 @@ M._request = function (url, callback, data, headers,methed) {
225
225
 
226
226
  //合并请求头
227
227
  headers = privateObj.getFunctionOrObjResult(M.reqComHeaders, headers)
228
- var options = {
228
+ let options = {
229
229
  hostname: urlObj.hostname,
230
230
  port: urlObj.port,
231
231
  path: urlObj.path,
@@ -244,7 +244,7 @@ M._request = function (url, callback, data, headers,methed) {
244
244
  }
245
245
 
246
246
  return new Promise((resolve, reject) => {
247
- var req = reqHttp.request(options, function (res) {
247
+ let req = reqHttp.request(options, function (res) {
248
248
  options = M.httpBefore(options);
249
249
  if (options == false) {
250
250
  return;
@@ -296,10 +296,10 @@ M.postJson = function (url, callback, data, headers) {
296
296
  };
297
297
  }
298
298
  url = privateObj.appendDataToUrl(url, M.reqComQueryparams);
299
- var html = '';
300
- var urlObj = url_module.parse(url)
299
+ let html = '';
300
+ let urlObj = url_module.parse(url)
301
301
  //发送 http Post 请求
302
- var postData = JSON.stringify(data);
302
+ let postData = JSON.stringify(data);
303
303
  if (!headers) {
304
304
  headers = {
305
305
  'Content-Type': 'application/json; ' +
@@ -309,7 +309,7 @@ M.postJson = function (url, callback, data, headers) {
309
309
  }
310
310
  //合并请求头
311
311
  headers = privateObj.getFunctionOrObjResult(M.reqComHeaders, headers)
312
- var options = {
312
+ let options = {
313
313
  hostname: urlObj.hostname,
314
314
  port: urlObj.port,
315
315
  path: urlObj.path,
@@ -329,7 +329,7 @@ M.postJson = function (url, callback, data, headers) {
329
329
 
330
330
  return new Promise((resolve, reject) => {
331
331
 
332
- var req = reqHttp.request(options, function (res) {
332
+ let req = reqHttp.request(options, function (res) {
333
333
  options = M.httpBefore(options);
334
334
  if (options == false) {
335
335
  return;
@@ -393,7 +393,8 @@ M.require =async function (url,noCache) {
393
393
  console.log("req require remote url:", url);
394
394
  let promise = new Promise(function (reslove, reject) {
395
395
  require(ht).get(url, function (req, res) {
396
- var d = '';
396
+ res.setEncoding('utf-8');
397
+ let d = '';
397
398
  req.on('data', (data) => {
398
399
  d += data;
399
400
  });
@@ -444,7 +445,7 @@ M.import=async function (url,callback){
444
445
  *下载图片
445
446
  */
446
447
  M.download =async function (url, file) {
447
- var func = http;
448
+ let func = http;
448
449
  if (url.indexOf("https") >= 0) {
449
450
  func = https;
450
451
  }
@@ -464,23 +465,24 @@ M.download =async function (url, file) {
464
465
  *下载所有图片
465
466
  */
466
467
  M.downloadAllImg = function (url, file, callback) {
467
- var urlObj = url_module.parse(url)
468
- var options = {
468
+ let urlObj = url_module.parse(url)
469
+ let options = {
469
470
  hostname: urlObj.hostname,
470
471
  }
471
- var func = http;
472
+ let func = http;
472
473
  if (url.indexOf("https") >= 0) {
473
474
  func = https;
474
475
  }
475
- var req = func.request(options, function (res) {
476
+ let req = func.request(options, function (res) {
477
+ res.setEncoding('utf-8');
476
478
  res.on('data', function (data) {
477
479
  //Buffer
478
- var string = data.toString();
479
- var rule = /https?:\/\/.[^"]+\.(png|jpg|gif|jpeg)/gi;
480
- var ary = string.match(rule); //拿到所有jpg结尾的链接集合
480
+ let string = data.toString();
481
+ let rule = /https?:\/\/.[^"]+\.(png|jpg|gif|jpeg)/gi;
482
+ let ary = string.match(rule); //拿到所有jpg结尾的链接集合
481
483
  if (callback) callback(ary);
482
- var x = 0;
483
- for (var i in ary) {
484
+ let x = 0;
485
+ for (let i in ary) {
484
486
  M.download(ary[i], file + (x++) + ary[i].substr(ary[i].lastIndexOf(".")));
485
487
  }
486
488
  });
@@ -599,8 +601,8 @@ M.mkdir = function (dirpath, dirname) {
599
601
  M.copyDir = function (src, dst) {
600
602
  let paths = fs.readdirSync(src); //同步读取当前目录
601
603
  paths.forEach(function (path) {
602
- var _src = src + '/' + path;
603
- var _dst = dst + '/' + path;
604
+ let _src = src + '/' + path;
605
+ let _dst = dst + '/' + path;
604
606
  fs.stat(_src, function (err, stats) { //stats 该对象 包含文件属性
605
607
  if (err) throw err;
606
608
  if (stats.isFile()) { //如果是个文件则拷贝
@@ -643,7 +645,7 @@ M.appendFile = function (file, str) {
643
645
  */
644
646
  M.getObjByFile = function (file) {
645
647
  data = M.readFile(file) || "[]"
646
- var obj = JSON.parse(data.toString());
648
+ let obj = JSON.parse(data.toString());
647
649
  return obj;
648
650
  }
649
651
  M.writeObjToFile = function (file, obj) {
@@ -652,7 +654,7 @@ M.writeObjToFile = function (file, obj) {
652
654
 
653
655
  M.addObjToFile = function (file, obj) {
654
656
  try {
655
- var d = M.getObjByFile(file);
657
+ let d = M.getObjByFile(file);
656
658
  M.writeObjToFile(file, [...d, obj]);
657
659
  } catch (e) {
658
660
  M.writeObjToFile(file, [obj]);
@@ -665,8 +667,8 @@ M.deleteObjByIdFile = function (file, id) {
665
667
  } else {
666
668
  ids = id;
667
669
  }
668
- var d = M.getObjByFile(file);
669
- var d1 = M.getObjByFile(file);
670
+ let d = M.getObjByFile(file);
671
+ let d1 = M.getObjByFile(file);
670
672
  let d_num = 0;
671
673
  for (let i = 0; i < d1.length; i++) {
672
674
  if (ids.indexOf(d1[i].id) >= 0) {
@@ -681,8 +683,8 @@ M.deleteObjByIdFile = function (file, id) {
681
683
  M.deleteObjByPropFile = function (file, o) {
682
684
  let o_key = Object.keys(o)[0];
683
685
  let o_val = o[o_key]
684
- var d = M.getObjByFile(file);
685
- var d1 = M.getObjByFile(file);
686
+ let d = M.getObjByFile(file);
687
+ let d1 = M.getObjByFile(file);
686
688
  let d_num = 0;
687
689
  for (let i = 0; i < d1.length; i++) {
688
690
  if (d1[i][o_key] == o_val) {
@@ -695,7 +697,7 @@ M.deleteObjByPropFile = function (file, o) {
695
697
  }
696
698
 
697
699
  M.updateObjByIdFile = function (file, obj) {
698
- var d = M.getObjByFile(file);
700
+ let d = M.getObjByFile(file);
699
701
  for (let i = 0; i < d.length; i++) {
700
702
  if (d[i].id == obj.id) {
701
703
  d.splice(i, 1, Object.assign(d[i],obj));
@@ -705,7 +707,7 @@ M.updateObjByIdFile = function (file, obj) {
705
707
  M.writeObjToFile(file, d);
706
708
  }
707
709
  M.getObjByIdFile = function (file, id) {
708
- var d = M.getObjByFile(file);
710
+ let d = M.getObjByFile(file);
709
711
  for (let i = 0; i < d.length; i++) {
710
712
  if (d[i].id == id) {
711
713
  return d[i];
@@ -713,7 +715,7 @@ M.getObjByIdFile = function (file, id) {
713
715
  }
714
716
  }
715
717
  M.listAllObjByPropFile = function (file, caseObj) {
716
- var d = M.getObjByFile(file);
718
+ let d = M.getObjByFile(file);
717
719
  let o_keys = Object.keys(caseObj);
718
720
  if (caseObj && o_keys.length>0) {
719
721
  let r_list = [];
@@ -814,13 +816,14 @@ M.getAttribute = function (k) {
814
816
  M.readLine =async function (file, callback) {
815
817
  let lineCount=0;
816
818
  return new Promise((resolve, reject) =>{
817
- var remaining = '';
818
- var input = fs.createReadStream(file);
819
+ let remaining = '';
820
+ let input = fs.createReadStream(file);
821
+ input.setEncoding('utf-8');
819
822
  input.on('data', function (data) {
820
823
  remaining += data;
821
- var index = remaining.indexOf('\n');
824
+ let index = remaining.indexOf('\n');
822
825
  while (index > -1) {
823
- var line = remaining.substring(0, index);
826
+ let line = remaining.substring(0, index);
824
827
  remaining = remaining.substring(index + 1);
825
828
  lineCount++;
826
829
  callback(line);
@@ -836,8 +839,33 @@ M.readLine =async function (file, callback) {
836
839
 
837
840
 
838
841
  M.readCsvLine =async function (file, callback) {
842
+ function parseStringToArray(str) {
843
+ const result = [];
844
+ let temp = '';
845
+ let inQuotes = false;
846
+ for (let i = 0; i < str.length; i++) {
847
+ const char = str[i];
848
+ if (char === ',' && !inQuotes) {
849
+ result.push(temp.trim());
850
+ temp = '';
851
+ } else if (char === '"') {
852
+ if (inQuotes && str[i + 1] === '"') {
853
+ temp += '"';
854
+ i++;
855
+ } else {
856
+ inQuotes = !inQuotes;
857
+ }
858
+ } else {
859
+ temp += char;
860
+ }
861
+ }
862
+
863
+ result.push(temp.trim());
864
+
865
+ return result;
866
+ }
839
867
  return M.readLine(file, function (line) {
840
- callback(line.replace("\r", "").split(/(?<!\"[^,]+),(?![^,]+\")/));
868
+ callback(parseStringToArray(line));
841
869
  })
842
870
  }
843
871
 
@@ -855,7 +883,7 @@ M.getFileList = function (path) {
855
883
  function walk(file) {
856
884
  states = fs.statSync(path + '/' + file);
857
885
  if (states.isDirectory()) {
858
- var item;
886
+ let item;
859
887
  if (targetObj["children"]) {
860
888
  item = {name: file, children: [], value: path + '/' + file};
861
889
  targetObj["children"].push(item);
@@ -867,24 +895,24 @@ M.getFileList = function (path) {
867
895
  readFile(path + '/' + file, filesList, item);
868
896
  } else {
869
897
  //创建一个对象保存信息
870
- var obj = new Object();
898
+ let obj = new Object();
871
899
  obj.size = states.size;//文件大小,以字节为单位
872
900
  obj.name = file;//文件名
873
901
  obj.path = path + '/' + file; //文件绝对路径
874
902
 
875
903
  if (targetObj["children"]) {
876
- var item = {name: file, value: obj.path}
904
+ let item = {name: file, value: obj.path}
877
905
  targetObj["children"].push(item);
878
906
  } else {
879
- var item = {name: file, value: obj.path};
907
+ let item = {name: file, value: obj.path};
880
908
  filesList.push(item);
881
909
  }
882
910
  }
883
911
  }
884
912
  }
885
913
 
886
- var filesList = [];
887
- var targetObj = {};
914
+ let filesList = [];
915
+ let targetObj = {};
888
916
  readFile(path, filesList, targetObj);
889
917
  return filesList;
890
918
  }
@@ -897,7 +925,7 @@ M.getFileDirList = function (path) {
897
925
  function walk(file) {
898
926
  states = fs.statSync(path + '/' + file);
899
927
  if (states.isDirectory()) {
900
- var item;
928
+ let item;
901
929
  let dir=path + '/' + file;
902
930
  if(dir.indexOf("lib")==-1){
903
931
  dirList.push(path + '/' + file)
@@ -913,9 +941,9 @@ M.getFileDirList = function (path) {
913
941
  }
914
942
  }
915
943
  }
916
- var dirList=[]
917
- var filesList = [];
918
- var targetObj = {};
944
+ let dirList=[]
945
+ let filesList = [];
946
+ let targetObj = {};
919
947
  readFile(path, filesList, targetObj);
920
948
  return dirList;
921
949
  }
@@ -967,10 +995,10 @@ M.getSqlite = function (dbName) {
967
995
  if (M.sqlite) {
968
996
  return M.sqlite;
969
997
  }
970
- var SQLite3 = require('sqlite3').verbose();
971
- var Db = new SQLite3.Database(dbName || "ming_autotest.db");
998
+ let SQLite3 = require('sqlite3').verbose();
999
+ let Db = new SQLite3.Database(dbName || "ming_autotest.db");
972
1000
  Db.doSql = function doSql(sql) {
973
- var promise = new Promise(function (reslove, reject) {
1001
+ let promise = new Promise(function (reslove, reject) {
974
1002
  if (Db.display_sql_enable) {
975
1003
  M.log(sql)
976
1004
  }
@@ -1008,7 +1036,7 @@ M.getMySql = function (dbConfig) {
1008
1036
  if (M.mysql) {
1009
1037
  return M.mysql;
1010
1038
  }
1011
- var mysql = require('mysql');
1039
+ let mysql = require('mysql');
1012
1040
  let defaultDbConfig = {
1013
1041
  "host": dbConfig.host || "localhost",
1014
1042
  "user": dbConfig.user || "root",
@@ -1019,10 +1047,10 @@ M.getMySql = function (dbConfig) {
1019
1047
  dateStrings: true,
1020
1048
  timezone: "08:00"
1021
1049
  }
1022
- var Db = {};
1050
+ let Db = {};
1023
1051
  Db.dbConfig=defaultDbConfig;
1024
1052
  console.log("connect mysql", defaultDbConfig)
1025
- var pool = mysql.createPool(defaultDbConfig);
1053
+ let pool = mysql.createPool(defaultDbConfig);
1026
1054
  Db.pool=pool;
1027
1055
  Db.getConnection= function(callback){
1028
1056
  return new Promise(((resolve, reject) => {
@@ -1039,7 +1067,7 @@ M.getMySql = function (dbConfig) {
1039
1067
  if (Db.display_sql_enable) {
1040
1068
  M.log(sql)
1041
1069
  }
1042
- var promise = new Promise(function (reslove, reject) {
1070
+ let promise = new Promise(function (reslove, reject) {
1043
1071
  pool.getConnection(function (err, connection) {
1044
1072
  connection.query(sql, params, function (err, rows) {
1045
1073
  if (err) {
@@ -1062,7 +1090,7 @@ M.getMySql = function (dbConfig) {
1062
1090
  if (Db.display_sql_enable) {
1063
1091
  M.log(sql)
1064
1092
  }
1065
- var promise = new Promise(function (reslove, reject) {
1093
+ let promise = new Promise(function (reslove, reject) {
1066
1094
  connection.query(sql, params, function (err, rows) {
1067
1095
  if (err) {
1068
1096
  reject(err);
@@ -1111,11 +1139,11 @@ M.getMongoDB = function (dbConfig) {
1111
1139
  if (M.mongoDb) {
1112
1140
  return M.mongoDb;
1113
1141
  }
1114
- var MongoDB=require('mongodb');
1115
- var MongoClient =MongoDB.MongoClient;
1142
+ let MongoDB=require('mongodb');
1143
+ let MongoClient =MongoDB.MongoClient;
1116
1144
  const ObjectID = MongoDB.ObjectID;
1117
1145
 
1118
- var Config={
1146
+ let Config={
1119
1147
  dbUrl: dbConfig.dbUrl|| 'mongodb://localhost:27017/',
1120
1148
  dbName: dbConfig.dbName|| 'miapi'
1121
1149
  };
@@ -1146,7 +1174,7 @@ M.getMongoDB = function (dbConfig) {
1146
1174
  }
1147
1175
  return new Promise((resolve,reject)=>{
1148
1176
  MingMongoClient.connect().then((db)=>{
1149
- var result=db.collection(collectionName).find(json);
1177
+ let result=db.collection(collectionName).find(json);
1150
1178
  result.toArray(function(err,docs){
1151
1179
  if(err){
1152
1180
  reject(err);
@@ -1242,7 +1270,7 @@ M.getMongoDB = function (dbConfig) {
1242
1270
  }
1243
1271
  return new Promise((resolve,reject)=>{
1244
1272
  MingMongoClient.connect().then((db)=>{
1245
- var whereArgs = {
1273
+ let whereArgs = {
1246
1274
  _id: new ObjectID(id)
1247
1275
  };
1248
1276
  db.collection(collectionName).findOne(whereArgs,{},function(err,result){
@@ -1271,8 +1299,8 @@ M.getMongoDB = function (dbConfig) {
1271
1299
  * ----------------------Sql CRUD START-------------------------------------------
1272
1300
  */
1273
1301
  M.getInsertObjSql = function (tableName, obj) {
1274
- var fields = "(";
1275
- var values = "(";
1302
+ let fields = "(";
1303
+ let values = "(";
1276
1304
  for (let field in obj) {
1277
1305
  fields += field + ",";
1278
1306
  values += `'${obj[field]}'` + ",";
@@ -1286,7 +1314,7 @@ M.getInsertObjSql = function (tableName, obj) {
1286
1314
  }
1287
1315
 
1288
1316
  M.getDeleteObjSql = function (tableName, obj) {
1289
- var fields = [];
1317
+ let fields = [];
1290
1318
  for (let field in obj) {
1291
1319
  fields.push(field);
1292
1320
  }
@@ -1296,7 +1324,7 @@ M.getDeleteObjSql = function (tableName, obj) {
1296
1324
  }
1297
1325
 
1298
1326
  M.getUpdateObjSql = function (tableName, obj, caseObj) {
1299
- var fields = [];
1327
+ let fields = [];
1300
1328
  for (let field in obj) {
1301
1329
  if (field != "id")
1302
1330
  fields.push(field);
@@ -1305,7 +1333,7 @@ M.getUpdateObjSql = function (tableName, obj, caseObj) {
1305
1333
  if (!caseObj) {
1306
1334
  sql = `update ${tableName} set ${fields.map(u => u + "='" + obj[u] + "'")} where id=${obj.id}`;
1307
1335
  } else {
1308
- var caseObjfields = [];
1336
+ let caseObjfields = [];
1309
1337
  for (let caseObjfield in caseObj) {
1310
1338
  caseObjfields.push(caseObjfield)
1311
1339
  }
@@ -1317,7 +1345,7 @@ M.getUpdateObjSql = function (tableName, obj, caseObj) {
1317
1345
 
1318
1346
 
1319
1347
  M.getSelectObjSql = function (tableName, obj) {
1320
- var fields = [];
1348
+ let fields = [];
1321
1349
  for (let field in obj) {
1322
1350
  fields.push(field);
1323
1351
  }
@@ -1343,7 +1371,7 @@ M.getSelectObjSql = function (tableName, obj) {
1343
1371
  *封装返回数据
1344
1372
  */
1345
1373
  M.result = function (data, success,message) {
1346
- var r = {};
1374
+ let r = {};
1347
1375
  if (success == false) {
1348
1376
  r.code = -2;
1349
1377
  r.msg = message||"操作失败";
@@ -1353,7 +1381,7 @@ M.result = function (data, success,message) {
1353
1381
  }
1354
1382
  r.requestId=M.req? M.req.requestId:"";
1355
1383
  try {
1356
- var obj = JSON.parse(data);
1384
+ let obj = JSON.parse(data);
1357
1385
  if (typeof obj == 'object' && obj) {
1358
1386
  r.data = obj;
1359
1387
  } else {
@@ -1386,7 +1414,7 @@ M.failResult=(msg,code,d)=>{
1386
1414
  *获取下划线式的对象
1387
1415
  */
1388
1416
  M.getUnderlineObj = function (obj) {
1389
- var result = {};
1417
+ let result = {};
1390
1418
  for (let field in obj) {
1391
1419
  result[field.humpToUnderline()] = obj[field]
1392
1420
  }
@@ -1397,7 +1425,7 @@ M.getUnderlineObj = function (obj) {
1397
1425
  *获取驼峰式的对象
1398
1426
  */
1399
1427
  M.getHumpObj = function (obj) {
1400
- var result = {};
1428
+ let result = {};
1401
1429
  for (let field in obj) {
1402
1430
  result[field.underlineToHump()] = obj[field]
1403
1431
  }
@@ -1410,14 +1438,14 @@ M.randomStr = function () {
1410
1438
 
1411
1439
  M.urlStringify = function (obj) {
1412
1440
  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 + "=";
1441
+ let keys = Object.keys(obj);
1442
+ let len = keys.length;
1443
+ let flast = len - 1;
1444
+ let fields = '';
1445
+ for (let i = 0; i < len; ++i) {
1446
+ let k = keys[i];
1447
+ let v = obj[k];
1448
+ let ks = k + "=";
1421
1449
  fields += ks + v;
1422
1450
  if (i < flast)
1423
1451
  fields += "&";
@@ -1429,12 +1457,12 @@ M.urlStringify = function (obj) {
1429
1457
 
1430
1458
  M.urlParse = function (url) {
1431
1459
  url = url.substr(url.indexOf("?") + 1);
1432
- var t, n, r, i = url, s = {};
1460
+ let t, n, r, i = url, s = {};
1433
1461
  t = i.split("&"),
1434
1462
  r = null,
1435
1463
  n = null;
1436
- for (var o in t) {
1437
- var u = t[o].indexOf("=");
1464
+ for (let o in t) {
1465
+ let u = t[o].indexOf("=");
1438
1466
  u !== -1 && (r = t[o].substr(0, u),
1439
1467
  n = t[o].substr(u + 1),
1440
1468
  s[r] = n)
@@ -1457,7 +1485,7 @@ M.err = function (e) {
1457
1485
 
1458
1486
 
1459
1487
  M.server = function () {
1460
- var G = this; /*全局变量,也就是M*/
1488
+ let G = this; /*全局变量,也就是M*/
1461
1489
  //静态资源路径
1462
1490
  this._views = "static";
1463
1491
  //key为去除rest参数的url,val为原始url
@@ -1479,8 +1507,9 @@ M.server = function () {
1479
1507
  //如果实现此函数,则只能有一个此服务
1480
1508
  this._server = function () {
1481
1509
  };
1482
- var app =async function (req, res) {
1510
+ let app =async function (req, res) {
1483
1511
  try {
1512
+ req.setEncoding('utf-8');
1484
1513
  M.req=req;
1485
1514
  M.res=res;
1486
1515
  //是否已经发送过了
@@ -1497,7 +1526,7 @@ M.server = function () {
1497
1526
  //是否为rest请求
1498
1527
  req.isRestRequest = function () {
1499
1528
  if (Object.keys(G._rest).length == 0) return false;
1500
- var isRest = false;
1529
+ let isRest = false;
1501
1530
  for (let i = 0; i < Object.keys(G._rest).length; i++) {
1502
1531
  if (pathname.startsWith(Object.keys(G._rest)[i])) {
1503
1532
  isRest = true;
@@ -1579,9 +1608,9 @@ M.server = function () {
1579
1608
  if (!isString) {
1580
1609
  text = JSON.stringify(text);
1581
1610
  }
1582
- var pathname = url_module.parse(url).pathname; /*获取url的值*/
1611
+ let pathname = url_module.parse(url).pathname; /*获取url的值*/
1583
1612
  //获取文件的后缀名
1584
- var extname = path.extname(pathname);
1613
+ let extname = path.extname(pathname);
1585
1614
  res.writeHead(200, {"Content-Type": "" + (privateObj.staticMime[extname] || 'text/html') + ";charset='utf-8'",});
1586
1615
  res.write(text);
1587
1616
  res.end();
@@ -1608,7 +1637,7 @@ M.server = function () {
1608
1637
  throw e;
1609
1638
  }).pipe(res);
1610
1639
  }else {
1611
- var func = http;
1640
+ let func = http;
1612
1641
  if (url.indexOf("https") >= 0) {
1613
1642
  func = https;
1614
1643
  }
@@ -1647,9 +1676,9 @@ M.server = function () {
1647
1676
  if (!isString) {
1648
1677
  text = JSON.stringify(text);
1649
1678
  }
1650
- var pathname = url_module.parse(url).pathname; /*获取url的值*/
1679
+ let pathname = url_module.parse(url).pathname; /*获取url的值*/
1651
1680
  //获取文件的后缀名
1652
- var extname = path.extname(pathname);
1681
+ let extname = path.extname(pathname);
1653
1682
  res.writeHead(200, {"Content-Type": "" + (privateObj.staticMime[extname] || 'text/html') + ";charset='utf-8'",});
1654
1683
  let templateStr=""
1655
1684
  try {
@@ -1694,13 +1723,13 @@ M.server = function () {
1694
1723
  res.end();
1695
1724
  }
1696
1725
  //获取路由
1697
- var pathname = url_module.parse(req.url).pathname;
1726
+ let pathname = url_module.parse(req.url).pathname;
1698
1727
  if (!pathname.endsWith('/')) {
1699
1728
  pathname = pathname + '/';
1700
1729
  }
1701
1730
  // pathname.startsWith("/usr/")
1702
1731
  //获取请求的方式 get post
1703
- var method = req.method.toLowerCase();
1732
+ let method = req.method.toLowerCase();
1704
1733
  if (req.isStaticRequest()) {
1705
1734
 
1706
1735
  await G._begin(req, res);
@@ -1710,7 +1739,7 @@ M.server = function () {
1710
1739
 
1711
1740
  //为req加个params用于存放请求参数
1712
1741
  req.params = {};
1713
- var mapingPath = "";
1742
+ let mapingPath = "";
1714
1743
  //如果是rest风格的请求,为其封装请求参数
1715
1744
  if (req.isRestRequest()) {
1716
1745
  for (let i = 0; i < Object.keys(G._rest).length; i++) {
@@ -1719,7 +1748,7 @@ M.server = function () {
1719
1748
  mapingPath = G._rest[pathname];
1720
1749
  }
1721
1750
  }
1722
- var realPathName = url_module.parse(req.url).pathname;
1751
+ let realPathName = url_module.parse(req.url).pathname;
1723
1752
  if (!realPathName.endsWith('/')) {
1724
1753
  realPathName = realPathName + '/';
1725
1754
  }
@@ -1742,7 +1771,7 @@ M.server = function () {
1742
1771
  method == "delete"
1743
1772
  ) && (G['_' + method][pathname])) {
1744
1773
  if (method != 'get') { /*执行post请求*/
1745
- var postStr = '';
1774
+ let postStr = '';
1746
1775
  req.on('data', function (chunk) {
1747
1776
  postStr += chunk;
1748
1777
  })
@@ -1859,7 +1888,7 @@ M.server = function () {
1859
1888
  app.get = function (url, callback) {
1860
1889
  const single=(url,callback)=>{
1861
1890
  url = M.formatUrl(url);
1862
- var realUrl = url;
1891
+ let realUrl = url;
1863
1892
  if (url.indexOf(":") > 0) {
1864
1893
  url = url.substr(0, url.indexOf(":"));
1865
1894
  G._rest[url] = realUrl;
@@ -1874,7 +1903,7 @@ M.server = function () {
1874
1903
  app.post = function (url, callback) {
1875
1904
  const single=(url,callback)=>{
1876
1905
  url = M.formatUrl(url);
1877
- var realUrl = url;
1906
+ let realUrl = url;
1878
1907
  if (url.indexOf(":") > 0) {
1879
1908
  url = url.substr(0, url.indexOf(":"));
1880
1909
  G._rest[url] = realUrl;
@@ -1887,7 +1916,7 @@ M.server = function () {
1887
1916
  app.put = function (url, callback) {
1888
1917
  const single=(url,callback)=>{
1889
1918
  url = M.formatUrl(url);
1890
- var realUrl = url;
1919
+ let realUrl = url;
1891
1920
  if (url.indexOf(":") > 0) {
1892
1921
  url = url.substr(0, url.indexOf(":"));
1893
1922
  G._rest[url] = realUrl;
@@ -1900,7 +1929,7 @@ M.server = function () {
1900
1929
  app.delete = function (url, callback) {
1901
1930
  const single=(url,callback)=>{
1902
1931
  url = M.formatUrl(url);
1903
- var realUrl = url;
1932
+ let realUrl = url;
1904
1933
  if (url.indexOf(":") > 0) {
1905
1934
  url = url.substr(0, url.indexOf(":"));
1906
1935
  G._rest[url] = realUrl;
@@ -1915,7 +1944,7 @@ M.server = function () {
1915
1944
  app.mapping = function (url, callback) {
1916
1945
  const single=(url,callback)=>{
1917
1946
  url = M.formatUrl(url);
1918
- var realUrl = url;
1947
+ let realUrl = url;
1919
1948
  if (url.indexOf(":") > 0) {
1920
1949
  url = url.substr(0, url.indexOf(":"));
1921
1950
  G._rest[url] = realUrl;
@@ -2029,6 +2058,7 @@ M.getAxiosConfig = async (req) => {
2029
2058
  axiosConfig.method = req.method.toLocaleLowerCase();
2030
2059
  axiosConfig.headers = req.headers
2031
2060
  let postStr = '';
2061
+ req.setEncoding('utf-8');
2032
2062
  req.on('data', function (chunk) {
2033
2063
  postStr += chunk;
2034
2064
  })
@@ -2052,8 +2082,8 @@ M.getAxiosConfig = async (req) => {
2052
2082
 
2053
2083
  M.axios = function (axiosConfig) {
2054
2084
  axiosConfig.headers.host = "";
2055
- var urlObj = url_module.parse(axiosConfig.url)
2056
- var options = {
2085
+ let urlObj = url_module.parse(axiosConfig.url)
2086
+ let options = {
2057
2087
  hostname: urlObj.hostname,
2058
2088
  port: urlObj.port,
2059
2089
  path: urlObj.path,
@@ -2064,9 +2094,9 @@ M.axios = function (axiosConfig) {
2064
2094
  if (axiosConfig.url.startsWith("https")) {
2065
2095
  reqHttp = https;
2066
2096
  }
2067
- var html = '';
2097
+ let html = '';
2068
2098
  return new Promise((resolve, reject) => {
2069
- var req = reqHttp.request(options, function (res) {
2099
+ let req = reqHttp.request(options, function (res) {
2070
2100
  options = M.httpBefore(options);
2071
2101
  if (options == false) {
2072
2102
  return;
@@ -2108,13 +2138,13 @@ privateObj.dealUseServer = async function (req, res) {
2108
2138
 
2109
2139
  privateObj.staticServer = async function (req, res, staticPath) {
2110
2140
  if (res.alreadySend) return;
2111
- var pathname = url_module.parse(req.url).pathname; /*获取url的值*/
2141
+ let pathname = url_module.parse(req.url).pathname; /*获取url的值*/
2112
2142
  if (pathname == '/') {
2113
2143
  pathname = '/index.html'; /*默认加载的首页*/
2114
2144
  }
2115
2145
  let fileName = pathname.replace("/", "");
2116
2146
  //获取文件的后缀名
2117
- var extname = path.extname(pathname);
2147
+ let extname = path.extname(pathname);
2118
2148
 
2119
2149
  if (fileName.startsWith("__default_")) {
2120
2150
  res.setHeader("Access-Control-Allow-Origin", "*");
@@ -2265,7 +2295,7 @@ M.sseServer = function () {
2265
2295
  * ----------------------其他工具函数START--------------------------------------------
2266
2296
  */
2267
2297
  M.exec = function (comand) {
2268
- var promise = new Promise(function (reslove, reject) {
2298
+ let promise = new Promise(function (reslove, reject) {
2269
2299
  child_process.exec(comand, function (err, stdout, stderr) {
2270
2300
  if (err || stderr) console.error(err, stderr);
2271
2301
  reslove(stdout);
@@ -2276,11 +2306,11 @@ M.exec = function (comand) {
2276
2306
  }
2277
2307
 
2278
2308
  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];
2309
+ let interfaces = require('os').networkInterfaces();
2310
+ for (let devName in interfaces) {
2311
+ let iface = interfaces[devName];
2312
+ for (let i = 0; i < iface.length; i++) {
2313
+ let alias = iface[i];
2284
2314
  if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
2285
2315
  return alias.address;
2286
2316
  }
@@ -2299,8 +2329,8 @@ M.getMyIp = function () {
2299
2329
  */
2300
2330
 
2301
2331
  M.sleep = function (numberMillis) {
2302
- var now = new Date();
2303
- var exitTime = now.getTime() + numberMillis;
2332
+ let now = new Date();
2333
+ let exitTime = now.getTime() + numberMillis;
2304
2334
  while (true) {
2305
2335
  now = new Date();
2306
2336
  if (now.getTime() > exitTime)
@@ -2436,6 +2466,7 @@ privateObj.staticMime = {
2436
2466
  ".hdml": "text/x-hdml",
2437
2467
  ".hlp": "application/winhlp",
2438
2468
  ".hqx": "application/mac-binhex40",
2469
+ ".hex": "text/html",
2439
2470
  ".hta": "application/hta",
2440
2471
  ".htc": "text/x-component",
2441
2472
  ".htm": "text/html",
@@ -2651,7 +2682,6 @@ privateObj.staticMime = {
2651
2682
  ".setreg": "application/set-registration-initiation",
2652
2683
  ".sgm": "text/x-sgml",
2653
2684
  ".sgml": "text/x-sgml",
2654
- ".sh": "application/x-sh",
2655
2685
  ".shar": "application/x-shar",
2656
2686
  ".shtml": "magnus-internal/parsed-html",
2657
2687
  ".shw": "application/presentations",
@@ -2793,7 +2823,6 @@ privateObj.staticMime = {
2793
2823
  ".xlt": "application/vnd.ms-excel",
2794
2824
  ".xlw": "application/vnd.ms-excel",
2795
2825
  ".xm": "audio/x-mod",
2796
- ".xml": "text/plain",
2797
2826
  ".xml": "application/xml",
2798
2827
  ".xmz": "audio/x-mod",
2799
2828
  ".xof": "x-world/x-vrml",
@@ -2833,8 +2862,8 @@ privateObj.staticMime = {
2833
2862
  ".perl": "text/plain",
2834
2863
  ".php": "text/plain",
2835
2864
  ".py": "text/plain",
2865
+ ".json5": "text/plain",
2836
2866
  ".redis": "text/plain",
2837
- ".conf": "text/conf",
2838
2867
  ".sql": "text/sql",
2839
2868
  ".ejs": "text/plain"
2840
2869
  }
@@ -2863,7 +2892,7 @@ M.init = function () {
2863
2892
  * 下划线命名转为驼峰命名
2864
2893
  */
2865
2894
  String.prototype.underlineToHump = function () {
2866
- var re = /_(\w)/g;
2895
+ let re = /_(\w)/g;
2867
2896
  str = this.replace(re, function ($0, $1) {
2868
2897
  return $1.toUpperCase();
2869
2898
  });
@@ -2874,7 +2903,7 @@ M.init = function () {
2874
2903
  * 驼峰命名转下划线
2875
2904
  */
2876
2905
  String.prototype.humpToUnderline = function () {
2877
- var re = /_(\w)/g;
2906
+ let re = /_(\w)/g;
2878
2907
  str = this.replace(/([A-Z])/g, "_$1").toLowerCase();
2879
2908
  return str;
2880
2909
  }
@@ -2893,7 +2922,7 @@ M.init = function () {
2893
2922
  }
2894
2923
  //格式化日期
2895
2924
  Date.prototype.format = function (fmt) {
2896
- var o = {
2925
+ let o = {
2897
2926
  "M+": this.getMonth() + 1, //月份
2898
2927
  "d+": this.getDate(), //日
2899
2928
  "h+": this.getHours(), //小时
@@ -2905,7 +2934,7 @@ M.init = function () {
2905
2934
  if (/(y+)/.test(fmt)) {
2906
2935
  fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
2907
2936
  }
2908
- for (var k in o) {
2937
+ for (let k in o) {
2909
2938
  if (new RegExp("(" + k + ")").test(fmt)) {
2910
2939
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
2911
2940
  }
@@ -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.2"
50
50
  }