utils.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. 'use strict';
  2. const crypto = require('crypto');
  3. const fs = require('fs');
  4. const path = require('path');
  5. const readline = require('readline');
  6. const net = require('net');
  7. exports = module.exports;
  8. // control variable of func "myPrint"
  9. const isPrintFlag = true;
  10. /**
  11. * Check and invoke callback function
  12. */
  13. exports.invokeCallback = function(cb) {
  14. if (!!cb && typeof cb === 'function') {
  15. cb.apply(null, Array.prototype.slice.call(arguments, 1));
  16. }
  17. };
  18. exports.size = function(obj) {
  19. if (!obj) {
  20. return 0;
  21. }
  22. let size = 0;
  23. for (const f in obj) {
  24. if (obj.hasOwnProperty(f)) {
  25. size++;
  26. }
  27. }
  28. return size;
  29. };
  30. // print the file name and the line number ~ begin
  31. function getStack() {
  32. const orig = Error.prepareStackTrace;
  33. Error.prepareStackTrace = function(_, stack) {
  34. return stack;
  35. };
  36. const err = new Error();
  37. Error.captureStackTrace(err, arguments.callee);
  38. const stack = err.stack;
  39. Error.prepareStackTrace = orig;
  40. return stack;
  41. }
  42. function getFileName(stack) {
  43. return stack[1].getFileName();
  44. }
  45. function getLineNumber(stack) {
  46. return stack[1].getLineNumber();
  47. }
  48. exports.myPrint = function() {
  49. if (isPrintFlag) {
  50. const len = arguments.length;
  51. if (len <= 0) {
  52. return;
  53. }
  54. const stack = getStack();
  55. let aimStr =
  56. "'" + getFileName(stack) + "' @" + getLineNumber(stack) + ' :\n';
  57. for (let i = 0; i < len; ++i) {
  58. aimStr +=
  59. (typeof arguments[i] === 'object'
  60. ? JSON.stringify(arguments[i])
  61. : arguments[i]) + ' ';
  62. }
  63. console.log('\n' + aimStr);
  64. }
  65. };
  66. exports.md5 = function(str) {
  67. const hash = crypto.createHash('md5');
  68. hash.update(str);
  69. return hash.digest('hex');
  70. };
  71. /*
  72. * 加密
  73. */
  74. exports.cipher = function(algorithm, key, iv, data) {
  75. key = new Buffer(key);
  76. iv = new Buffer(iv ? iv : 0);
  77. const cipher = crypto.createCipheriv(algorithm, key, iv);
  78. cipher.setAutoPadding(true); // default true
  79. let ciph = cipher.update(data, 'utf8', 'base64');
  80. ciph += cipher.final('base64');
  81. return ciph;
  82. };
  83. /*
  84. * 解密
  85. */
  86. exports.decipher = function(algorithm, key, iv, crypted) {
  87. key = new Buffer(key);
  88. iv = new Buffer(iv ? iv : '');
  89. const decipher = crypto.createDecipheriv(algorithm, key, iv);
  90. decipher.setAutoPadding(true);
  91. let decoded = decipher.update(crypted, 'base64', 'utf8');
  92. decoded += decipher.final('utf8');
  93. return decoded;
  94. };
  95. exports.getDate = function(flag) {
  96. if (!flag) {
  97. flag = '';
  98. }
  99. const date = new Date();
  100. const year = date.getFullYear();
  101. const month = date.getMonth() + 1;
  102. const day = date.getDate();
  103. const mytimes = year + flag + month + flag + day;
  104. return mytimes;
  105. };
  106. exports.dynamicSign = function(len) {
  107. len = len || 5;
  108. const chars = 'abcdefghijklmnopqrstuvwxyz';
  109. const maxPos = chars.length;
  110. let sign = '';
  111. for (let i = 0; i < len; i++) {
  112. sign += chars.charAt(Math.floor(Math.random() * maxPos));
  113. }
  114. return sign;
  115. };
  116. exports.toHump = function(str) {
  117. let result = '';
  118. const split = str.split('_');
  119. result += split[0];
  120. for (let i = 1; i < split.length; ++i) {
  121. result += split[i][0].toUpperCase() + split[i].substr(1);
  122. }
  123. return result;
  124. };
  125. exports.tryJsonParse = function(jsonStr, cb) {
  126. try {
  127. cb(null, JSON.parse(jsonStr));
  128. } catch (e) {
  129. cb(e, null);
  130. }
  131. };
  132. exports.mkdir = function(dirpath, dirname) {
  133. // 判断是否是第一次调用
  134. if (typeof dirname === 'undefined') {
  135. if (fs.existsSync(dirpath)) {
  136. return;
  137. }
  138. this.mkdir(dirpath, path.dirname(dirpath));
  139. } else {
  140. // 判断第二个参数是否正常,避免调用时传入错误参数
  141. if (dirname !== path.dirname(dirpath)) {
  142. this.mkdir(dirpath);
  143. return;
  144. }
  145. if (fs.existsSync(dirname)) {
  146. fs.mkdirSync(dirpath);
  147. } else {
  148. this.mkdir(dirname, path.dirname(dirname));
  149. fs.mkdirSync(dirpath);
  150. }
  151. }
  152. console.log('==> dir end', dirpath);
  153. };
  154. /*
  155. * 获取目录下指定后缀的所有文件
  156. * @param dir
  157. * @param ext
  158. * @return {Array}
  159. */
  160. exports.getAllFiles = function(dir, ext) {
  161. if (!dir) {
  162. return [];
  163. }
  164. const self = this;
  165. let extFiles = [];
  166. const files = fs.readdirSync(dir);
  167. files.forEach(function(file) {
  168. const pathname = path.join(dir, file);
  169. const stat = fs.lstatSync(pathname);
  170. if (stat.isDirectory()) {
  171. extFiles = extFiles.concat(self.getAllFiles(pathname, ext));
  172. } else if (path.extname(pathname) === ext) {
  173. extFiles.push(pathname.replace(cwd, '.'));
  174. }
  175. });
  176. return extFiles;
  177. };
  178. /*
  179. * 获取目录下所有文件夹
  180. */
  181. exports.getDirs = function(dir) {
  182. if (!dir) {
  183. return [];
  184. }
  185. const components = [];
  186. const files = fs.readdirSync(dir);
  187. files.forEach(function(item, index) {
  188. const stat = fs.lstatSync(dir + '/' + item);
  189. if (stat.isDirectory() === true) {
  190. components.push(item);
  191. }
  192. });
  193. return components;
  194. };
  195. exports.fileExist = function(filePath) {
  196. try {
  197. return fs.statSync(filePath).isFile();
  198. } catch (err) {
  199. return false;
  200. }
  201. };
  202. exports.delDir = function(path) {
  203. let files = [];
  204. if (fs.existsSync(path)) {
  205. files = fs.readdirSync(path);
  206. files.forEach((file, index) => {
  207. const curPath = path + '/' + file;
  208. if (fs.statSync(curPath).isDirectory()) {
  209. this.delDir(curPath); // 递归删除文件夹
  210. } else {
  211. fs.unlinkSync(curPath); // 删除文件
  212. }
  213. });
  214. fs.rmdirSync(path);
  215. }
  216. };
  217. exports.chmodPath = function(path, mode) {
  218. let files = [];
  219. if (fs.existsSync(path)) {
  220. files = fs.readdirSync(path);
  221. files.forEach((file, index) => {
  222. const curPath = path + '/' + file;
  223. if (fs.statSync(curPath).isDirectory()) {
  224. this.chmodPath(curPath, mode); // 递归删除文件夹
  225. } else {
  226. fs.chmodSync(curPath, mode);
  227. }
  228. });
  229. fs.chmodSync(path, mode);
  230. }
  231. };
  232. /**
  233. * 判断是否是同一天
  234. * @param d1
  235. * @param d2
  236. * @return {boolean}
  237. */
  238. exports.isSameDay = function(d1, d2) {
  239. return (
  240. d1.getFullYear() === d2.getFullYear() &&
  241. d1.getMonth() === d2.getMonth() &&
  242. d1.getDate() === d2.getDate()
  243. );
  244. };
  245. /*
  246. * 判断是否在有效期
  247. */
  248. exports.isInDate = function(createDate, days) {
  249. const diffDays = this.diffDays(createDate) + 1;
  250. return diffDays <= days;
  251. };
  252. /*
  253. * differ days
  254. * 返回两个日期相隔的天数
  255. * 按0点算
  256. * 1日0点与2日0点相隔为1天
  257. */
  258. exports.diffDays = function(createDate) {
  259. const tmp = new Date();
  260. tmp.setHours(0, 0, 0, 0);
  261. createDate.setHours(0, 0, 0, 0);
  262. return (tmp - createDate) / 24 / 3600000;
  263. };
  264. /*
  265. * differ weeks
  266. * 判断两个日期是否在同一周
  267. * add by mumu
  268. */
  269. exports.isSameWeek = function(old, now) {
  270. const oneDayTime = 1000 * 60 * 60 * 24;
  271. const old_count = parseInt(old.getTime() / oneDayTime);
  272. const now_other = parseInt(now.getTime() / oneDayTime);
  273. return parseInt((old_count + 4) / 7) == parseInt((now_other + 4) / 7);
  274. };
  275. /**
  276. * 读取json文件并解析
  277. * @param path
  278. * @return {any}
  279. */
  280. exports.loadJson = function(path) {
  281. return JSON.parse(fs.readFileSync(path).toString());
  282. };
  283. exports.getRandomArrayElements = function(arr, count) {
  284. let shuffled = arr.slice(0),
  285. i = arr.length,
  286. min = i - count,
  287. temp,
  288. index;
  289. while (i-- > min) {
  290. index = Math.floor((i + 1) * Math.random());
  291. temp = shuffled[index];
  292. shuffled[index] = shuffled[i];
  293. shuffled[i] = temp;
  294. }
  295. return shuffled.slice(min);
  296. };
  297. exports.getTodayExpireTime = function() {
  298. const endTime = new Date(new Date().setHours(23, 59, 59, 0)) / 1000;
  299. const expiresTime = endTime - Math.floor(new Date().getTime() / 1000);
  300. return expiresTime;
  301. };
  302. exports.objKeySort = function(obj) {
  303. const newkey = Object.keys(obj).sort();
  304. const newObj = {};
  305. for (let i = 0; i < newkey.length; i++) {
  306. newObj[newkey[i]] = obj[newkey[i]];
  307. }
  308. return newObj;
  309. };
  310. exports.serialize = function(obj) {
  311. const str = [];
  312. for (const p in obj) {
  313. if (obj.hasOwnProperty(p)) {
  314. str.push(p + '=' + obj[p]);
  315. }
  316. }
  317. return str.join('&');
  318. };
  319. exports.keepTwoDecimalFull = function(num) {
  320. let result = parseFloat(num);
  321. if (isNaN(result)) {
  322. return false;
  323. }
  324. result = Math.round(num * 100) / 100;
  325. let s_x = result.toString();
  326. let pos_decimal = s_x.indexOf('.');
  327. if (pos_decimal < 0) {
  328. pos_decimal = s_x.length;
  329. s_x += '.';
  330. }
  331. while (s_x.length <= pos_decimal + 2) {
  332. s_x += '0';
  333. }
  334. return s_x;
  335. };
  336. exports.sleep = function(time = 0) {
  337. return new Promise((resolve, reject) => {
  338. setTimeout(() => {
  339. resolve();
  340. }, time);
  341. });
  342. };
  343. /*
  344. * 按行读取文件内容
  345. * 返回:字符串数组
  346. * 参数:fReadName:文件名路径
  347. */
  348. exports.readFileToArr = async function(fReadName) {
  349. const fRead = fs.createReadStream(fReadName);
  350. const objReadline = readline.createInterface({
  351. input: fRead,
  352. });
  353. return new Promise((resolve, reject) => {
  354. const arr = [];
  355. objReadline.on('line', function(line) {
  356. arr.push(line);
  357. });
  358. objReadline.on('close', function() {
  359. resolve(arr);
  360. });
  361. });
  362. };
  363. exports.compareVersion = function(version, bigVersion) {
  364. version = version.split('.');
  365. bigVersion = bigVersion.split('.');
  366. for (let i = 0; i < version.length; i++) {
  367. version[i] = +version[i];
  368. bigVersion[i] = +bigVersion[i];
  369. if (version[i] > bigVersion[i]) {
  370. return false;
  371. } else if (version[i] < bigVersion[i]) {
  372. return true;
  373. }
  374. }
  375. return false;
  376. };
  377. exports.handleVersion = function(version) {
  378. if (!version) return version;
  379. version = version + '';
  380. if (version[0] === 'v') {
  381. return version.substr(1);
  382. }
  383. return version;
  384. };
  385. /*
  386. * 获取本机IP地址
  387. */
  388. exports.getIPAddress = function() {
  389. const interfaces = require('os').networkInterfaces();
  390. for (const devName in interfaces) {
  391. const iface = interfaces[devName];
  392. for (let i = 0; i < iface.length; i++) {
  393. const alias = iface[i];
  394. if (
  395. alias.family === 'IPv4' &&
  396. alias.address !== '127.0.0.1' &&
  397. !alias.internal
  398. ) {
  399. return alias.address;
  400. }
  401. }
  402. }
  403. };
  404. /*
  405. * 判断IP是否在同一网段
  406. */
  407. exports.isEqualIPAddress = function (addr1, addr2, mask = '255.255.255.0'){
  408. if(!addr1 || !addr2 || !mask){
  409. console.log("各参数不能为空");
  410. return false;
  411. }
  412. var
  413. res1 = [],
  414. res2 = [];
  415. addr1 = addr1.split(".");
  416. addr2 = addr2.split(".");
  417. mask = mask.split(".");
  418. for(var i = 0,ilen = addr1.length; i < ilen ; i += 1){
  419. res1.push(parseInt(addr1[i]) & parseInt(mask[i]));
  420. res2.push(parseInt(addr2[i]) & parseInt(mask[i]));
  421. }
  422. if(res1.join(".") == res2.join(".")){
  423. return true;
  424. }else{
  425. return false;
  426. }
  427. }
  428. /*
  429. * 端口是否被占用
  430. */
  431. exports.portIsOccupied = function portIsOccupied(port) {
  432. const server = net.createServer().listen(port, '0.0.0.0');
  433. return new Promise((resolve, reject) => {
  434. server.on('listening', () => {
  435. console.log(`the server is runnint on port ${port}`);
  436. server.close();
  437. resolve(false);
  438. });
  439. server.on('error', err => {
  440. if (err.code === 'EADDRINUSE') {
  441. resolve(true);
  442. console.log(`this port ${port} is occupied.try another.`);
  443. } else {
  444. resolve(true);
  445. }
  446. });
  447. });
  448. };