UNPKG

2.46 kBJavaScriptView Raw
1/**
2 * @file 开发时web调试服务器启动入口
3 * @author otakustay[otakustay@live.com],
4 * errorrik[errorrik@gmail.com],
5 * ostream[ostream.song@gmail.com],
6 * firede[firede@firede.us]
7 */
8
9
10/**
11 * 默认配置文件名
12 *
13 * @const
14 * @type {string}
15 */
16var DEFAULT_CONF_FILE = 'edp-webserver-config.js';
17
18/**
19 * 加载配置文件
20 *
21 * @inner
22 * @param {string=} confFile 配置文件路径
23 * @return {Object}
24 */
25function loadConf(confFile) {
26 var fs = require('fs');
27 var path = require('path');
28 var cwd = process.cwd();
29
30 if (confFile) {
31 confFile = path.resolve(cwd, confFile);
32 if (fs.existsSync(confFile)) {
33 return require(confFile);
34 }
35
36 return null;
37 }
38
39 var dir;
40 var parentDir = cwd;
41 do {
42 dir = parentDir;
43 confFile = path.resolve(dir, DEFAULT_CONF_FILE);
44 if (fs.existsSync(confFile)) {
45 return require(confFile);
46 }
47
48 parentDir = path.resolve(dir, '..');
49 } while (parentDir != dir);
50
51 return require('../index').getDefaultConfig();
52}
53
54/**
55 * 命令行配置项
56 *
57 * @inner
58 * @type {Object}
59 */
60var cli = {};
61
62/**
63 * 命令描述信息
64 *
65 * @type {string}
66 */
67cli.description = '启动EDP WebServer';
68
69/**
70 * 命令选项信息
71 *
72 * @type {Array}
73 */
74cli.options = [
75 'proxy:',
76 'port:',
77 'config:',
78 'document-root:'
79];
80
81/**
82 * 模块命令行运行入口
83 */
84cli.main = function (args, opts) {
85 var proxy = opts.proxy;
86 var port = opts.port;
87 var docRoot = opts['document-root'];
88 var conf = opts.config;
89
90 var path = require('path');
91 var fs = require('fs');
92 conf = loadConf(conf);
93
94 if (!conf) {
95 console.log('Cannot load server config.');
96 return;
97 }
98
99 if (docRoot) {
100 conf.documentRoot = path.resolve(process.cwd(), docRoot);
101 }
102
103 if (port) {
104 conf.port = port;
105 }
106
107 if (proxy) {
108 var proxyFile = path.resolve(process.cwd(), proxy);
109 if (fs.existsSync(proxyFile)) {
110 var content = fs.readFileSync(proxyFile, 'utf8');
111 conf.proxyMap = JSON.parse(content);
112 }
113 }
114
115 var start = require('../lib/start');
116
117 if (typeof conf.init === 'function') {
118 conf.init(conf, function(config){
119 start(config || conf);
120 });
121 }
122 else {
123 start(conf);
124 }
125};
126
127/**
128 * 命令行配置项
129 *
130 * @type {Object}
131 */
132exports.cli = cli;