utils.js 11 KB

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