index.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. 'use strict';
  2. const fs = require('fs');
  3. const os = require('os');
  4. const crypto = require('crypto');
  5. /**
  6. * Load *.json file synchronous. Don't use require('*.json')
  7. * to load *.json files, it will cached in process.
  8. * @param {String} filename absolute file path
  9. * @return {Object} a parsed object
  10. */
  11. exports.loadJSONSync = function (filename) {
  12. // strip BOM
  13. var content = fs.readFileSync(filename, 'utf8');
  14. if (content.charCodeAt(0) === 0xFEFF) {
  15. content = content.slice(1);
  16. }
  17. try {
  18. return JSON.parse(content);
  19. } catch (err) {
  20. err.message = filename + ': ' + err.message;
  21. throw err;
  22. }
  23. };
  24. /**
  25. * Encoding a string to Buffer safely
  26. * @param {String} str string.
  27. * @param {String} encoding. optional.
  28. * @return {Buffer} encoded buffer
  29. */
  30. exports.encode = function (str, encoding) {
  31. if (typeof str !== 'string') {
  32. str = '' + str;
  33. }
  34. return new Buffer(str, encoding);
  35. };
  36. /**
  37. * Generate a haser with specfied algorithm
  38. * @param {String} algorithm can be md5, etc.
  39. * @return {Function} a haser with specfied algorithm
  40. */
  41. exports.makeHasher = function (algorithm) {
  42. return function (data, encoding) {
  43. var shasum = crypto.createHash(algorithm);
  44. shasum.update(data);
  45. return shasum.digest(encoding);
  46. };
  47. };
  48. exports.createHash = exports.makeHasher;
  49. /**
  50. * Get md5 hash digests of data
  51. * @param {String|Buffer} data data.
  52. * @param {String} encoding optionnal. can be 'hex', 'binary', 'base64'.
  53. * @return {String|Buffer} if no encoding is provided, a buffer is returned.
  54. */
  55. exports.md5 = exports.makeHasher('md5');
  56. /**
  57. * Get sha1 hash digests of data
  58. * @param {String|Buffer} data data.
  59. * @param {String} key the key.
  60. * @param {String} encoding optionnal. can be 'hex', 'binary', 'base64'.
  61. * @return {String|Buffer} if no encoding is provided, a buffer is returned.
  62. */
  63. exports.createHmac = function (algorithm) {
  64. return function (data, key, encoding) {
  65. return crypto.createHmac(algorithm, key).update(data).digest(encoding);
  66. };
  67. };
  68. /**
  69. * Get sha1 hash digests of data
  70. * @param {String|Buffer} data data.
  71. * @param {String} key the key.
  72. * @param {String} encoding optionnal. can be 'hex', 'binary', 'base64'.
  73. * @return {String|Buffer} if no encoding is provided, a buffer is returned.
  74. */
  75. exports.sha1 = exports.createHmac('sha1');
  76. /**
  77. * Get a random value in a range
  78. * @param {Number} min range start.
  79. * @param {Number} max range end.
  80. */
  81. exports.random = function (min, max) {
  82. return Math.floor(min + Math.random() * (max - min));
  83. };
  84. /**
  85. * Generate a nonce string
  86. * @return {String} a nonce string.
  87. */
  88. exports.makeNonce = (function() {
  89. var counter = 0;
  90. var last;
  91. const machine = os.hostname();
  92. const pid = process.pid;
  93. return function () {
  94. var val = Math.floor(Math.random() * 1000000000000);
  95. if (val === last) {
  96. counter++;
  97. } else {
  98. counter = 0;
  99. }
  100. last = val;
  101. var uid = `${machine}${pid}${val}${counter}`;
  102. return exports.md5(uid, 'hex');
  103. };
  104. }());
  105. /**
  106. * Pad a number as \d\d format
  107. * @param {Number} num a number that less than 100.
  108. * @return {String} if number less than 10, pad with 0,
  109. * otherwise, returns string of number.
  110. */
  111. exports.pad2 = function (num) {
  112. if (num < 10) {
  113. return '0' + num;
  114. }
  115. return '' + num;
  116. };
  117. /**
  118. * Pad a number as \d\d\d format
  119. * @param {Number} num a number that less than 1000.
  120. * @return {String} if number less than 100, pad with 0,
  121. * otherwise, returns string of number.
  122. */
  123. exports.pad3 = function (num) {
  124. if (num < 10) {
  125. return '00' + num;
  126. } else if (num < 100) {
  127. return '0' + num;
  128. }
  129. return '' + num;
  130. };
  131. /**
  132. * Return the YYYYMMDD format of a date.
  133. * @param {Date} date a Date object.
  134. * @return {String} the YYYYMMDD format.
  135. */
  136. exports.getYYYYMMDD = function (date) {
  137. var YYYY = date.getFullYear();
  138. var MM = exports.pad2(date.getMonth() + 1);
  139. var DD = exports.pad2(date.getDate());
  140. return '' + YYYY + MM + DD;
  141. };
  142. /**
  143. * sleep a while.
  144. * @param {Number} in milliseconds
  145. * @return {Promise} a Promise
  146. */
  147. exports.sleep = function (ms) {
  148. return new Promise((resolve) => {
  149. setTimeout(resolve, ms);
  150. });
  151. };
  152. /**
  153. * Get the IPv4 address
  154. * @return {String} the IPv4 address, or empty string
  155. */
  156. exports.getIPv4 = function () {
  157. var interfaces = os.networkInterfaces();
  158. var keys = Object.keys(interfaces);
  159. for (var i = 0; i < keys.length; i++) {
  160. var key = keys[i];
  161. var addresses = interfaces[key];
  162. for (var j = 0; j < addresses.length; j++) {
  163. var item = addresses[j];
  164. if (!item.internal && item.family === 'IPv4') {
  165. return item.address;
  166. }
  167. }
  168. }
  169. // without non-internal address
  170. return '';
  171. };
  172. /**
  173. * Get the Mac address
  174. * @return {String} the Mac address
  175. */
  176. exports.getMac = function () {
  177. var interfaces = os.networkInterfaces();
  178. var keys = Object.keys(interfaces);
  179. for (var i = 0; i < keys.length; i++) {
  180. var key = keys[i];
  181. var addresses = interfaces[key];
  182. for (var j = 0; j < addresses.length; j++) {
  183. var item = addresses[j];
  184. if (!item.internal && item.family === 'IPv4') {
  185. return item.mac;
  186. }
  187. }
  188. }
  189. // without non-internal address
  190. return '00:00:00:00:00:00';
  191. };