core.js 8.1 KB

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