core.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. /**
  2. * @Author HonorLee (dev@honorlee.me)
  3. * @Version 1.0 (2018-05-04)
  4. * @License MIT
  5. */
  6. 'use strict';
  7. global.Core = {};
  8. global.CACHE = {};
  9. //Global Path
  10. global.Core.Path = {
  11. System : ROOTPATH + '/system',
  12. CoreLib : ROOTPATH + '/system/lib/core',
  13. ExtraLib : ROOTPATH + '/system/lib/extra',
  14. Helper : ROOTPATH + '/system/lib/helper',
  15. Work : ROOTPATH + '/app',
  16. Module : ROOTPATH + '/app/modules',
  17. Handler : ROOTPATH + '/app/handlers',
  18. View : ROOTPATH + '/app/view',
  19. Temp : ROOTPATH + '/temp',
  20. Session : ROOTPATH + '/temp/session',
  21. Log : ROOTPATH + '/log',
  22. Asset : ROOTPATH + '/' + Config.Asset.asset_path,
  23. Upload : ROOTPATH + '/' + Config.Asset.upload_path
  24. };
  25. //Global Extension Require
  26. global.serverUID = (Math.ceil(Math.random()*61439+4096)).toString(16).toUpperCase();
  27. global.Moment = require('moment-range').extendMoment(require('moment'));
  28. global.URL = require('url');
  29. global.Querystring = require('querystring');
  30. global.FILE = require('fs-extra');
  31. global.EJS = require('ejs');
  32. global.ASYNC = require('async');
  33. global.Base64 = require('js-base64');
  34. global.MD5 = require('md5');
  35. global.Formidable = require('formidable');
  36. global.MIME = require('mime-types');
  37. global.Path = require('path');
  38. global.Tracer = require('tracer').dailyfile({root:Core.Path.Log,format : "{{timestamp}} <{{title}}> {{file}}:{{line}} {{message}}", dateformat : "HH:MM:ss.L"});
  39. String.random = require('string-random');
  40. Core.Request = require('request');
  41. FILE.walkSync = require('klaw-sync');
  42. //System Library load
  43. let CoreLibFiles = FILE.readdirSync(Core.Path.CoreLib);
  44. CoreLibFiles.forEach(function(filename){
  45. let nameWithOutMimeType = (filename.split('.')[0]).toUpperCase();
  46. let coreClass;
  47. try {
  48. coreClass = require(Core.Path.CoreLib + '/' + filename);
  49. }catch(e){
  50. console.log('[Core] Core library file ['+filename+'] load error!');
  51. console.log(e);
  52. Tracer.error('[Core] Core library file ['+filename+'] load error!');
  53. }
  54. if(coreClass.hasOwnProperty('_name') && coreClass['_name']){
  55. global[coreClass['_name']] = coreClass;
  56. }else{
  57. global[nameWithOutMimeType] = coreClass;
  58. }
  59. if(typeof coreClass == 'object' && coreClass.hasOwnProperty('__construct')) coreClass['__construct']();
  60. });
  61. CoreLibFiles = null;
  62. //System Library load end
  63. //Core Setting,just change it if necessary!
  64. global.Core.Setting = {};
  65. //If Mysql on,load Mysql Extension
  66. if(Config && Config.Database.Mysql.on){
  67. let MysqlPool = require(Core.Path.ExtraLib + '/mysql-pool.js').instance(Config.Database.Mysql);
  68. let testMysqlCon = MysqlPool.getConnection(function(err,connection){
  69. if(!err){
  70. connection.release();
  71. connection.query('SELECT VERSION() as version',function(err,result,fields){
  72. if(err){
  73. LOGGER.error('Mysql Connect error,please recheck your config');
  74. LOGGER.error(err);
  75. }else{
  76. LOGGER.info('Mysql Connect success');
  77. LOGGER.info('Mysql Version: ' + result[0]['version'] + ' | User: ' + Config.Database.Mysql.user + ' | Database: ' + Config.Database.Mysql.database);
  78. global.MysqlPool = MysqlPool;
  79. global.MysqlDB = require(Core.Path.Helper + '/mysqldb.js');
  80. }
  81. });
  82. }else{
  83. LOGGER.error('Mysql Connect error,please recheck your config');
  84. LOGGER.error(err);
  85. }
  86. });
  87. }
  88. //If Mongodb on,load Mongodb Extension
  89. if(Config && Config.Database.Mongodb.on && Config.Database.Mongodb.database){
  90. let verify = Config.Database.Mongodb.user?Config.Database.Mongodb.user+':'+Config.Database.Mongodb.password+'@':'';
  91. let mongoConnect = 'mongodb://' + verify + Config.Database.Mongodb.host+':'+Config.Database.Mongodb.port+'/'+Config.Database.Mongodb.database;
  92. require('mongodb').MongoClient.connect(mongoConnect,function(err,db){
  93. if(err) {
  94. LOGGER.error('MongoDB connect error!',true);
  95. LOGGER.error('Server start failed. Log has been saved!');
  96. // Logger.out(err);
  97. return;
  98. }
  99. LOGGER.info('Mongodb Connect success');
  100. global.MongoDB = {db:db};
  101. global.MG = function(collection){
  102. if(!collection) return null;
  103. return MongoDB.db.collection(Config.Database.Mongodb.prefix+collection);
  104. };
  105. });
  106. }
  107. //If Memcache on,load Memcache Extension
  108. if(Config && Config.Database.Memcache.on){
  109. let Memclass = require('memcached');
  110. let Memcache = new Memclass(Config.Database.Memcache.host+':'+Config.Database.Memcache.port);
  111. Memcache.version(function(err,data){
  112. if(err){
  113. LOGGER.error('Memcache Connect error,please recheck your config');
  114. LOGGER.error(err);
  115. }else{
  116. LOGGER.info('Memcache Connect success');
  117. LOGGER.info('Memcache Version: ' + data[0]['version']);
  118. global.Memcache = Memcache;
  119. }
  120. });
  121. }
  122. //If Redis on,Create Redis Client
  123. if(Config && Config.Database.Redis.on){
  124. let redis = require('redis').createClient({port:Config.Database.Redis.port,host:Config.Database.Redis.host,retry_strategy: function (options) {
  125. if (options.error && options.error.code === 'ECONNREFUSED') {
  126. LOGGER.error('Redis connect has been refused,please recheck your config,and make sure redis server is running!');
  127. }
  128. if (options.total_retry_time > 1000 * 10) {
  129. LOGGER.error('Redis retry connect time exhausted');
  130. }
  131. if (options.attempt > 10) {
  132. LOGGER.error('Redis unknow error');
  133. }
  134. // reconnect after
  135. return Math.min(options.attempt * 100, 3000);
  136. },prefix:Config.Database.Redis.prefix});
  137. redis.on('ready',function(e){
  138. LOGGER.info('Redis Connect success');
  139. LOGGER.info('Redis Version: ' + redis.server_info.redis_version);
  140. global.Redis = redis;
  141. });
  142. redis.on('reconnecting',function(e){
  143. LOGGER.warning('Redis lost connect,reconnecting!');
  144. });
  145. }
  146. //Check File Paths
  147. for(let path in global.Core.Path){
  148. try{
  149. FILE.statSync(global.Core.Path[path]);
  150. }catch(e){
  151. FILE.mkdirsSync(global.Core.Path[path]);
  152. }
  153. }
  154. if(Config && Config.Wechat.on){
  155. global.Wechat = require(Core.Path.ExtraLib + '/wechat/wechat.js');
  156. try{
  157. FILE.statSync(Core.Path.Handler + Config.Wechat.handler_path +'/index.js');
  158. }catch(e){
  159. FILE.copy(Core.Path.ExtraLib + '/wechat/handler/wechat.js',Core.Path.Handler + Config.Wechat.handler_path +'/index.js')
  160. }
  161. }
  162. // let HandlerFiles = FILE.walkSync(Core.Path.Handler, {nodir: true});
  163. // CACHE.Handlers = [];
  164. // for(let i in HandlerFiles){
  165. // let path = HandlerFiles[i]['path'];
  166. // CACHE.Handlers.push(path.replace(Core.Path.Handler,''));
  167. // }
  168. // CACHE.HandlersString = CACHE.Handlers.join('|');
  169. global.RouterRule = null;
  170. try{
  171. global.RouterRule = require(ROOTPATH+'/rule.js');
  172. }catch(e){}