UNPKG

3.01 kBJavaScriptView Raw
1var fs = require('fs'),
2 path = require('path'),
3 http = require('http'),
4 https = require('https'),
5 connect = require('connect'),
6 argv = require('yargs').argv,
7 serveIndex = require('serve-index'),
8 print = require('../../utils/print'),
9 logger = require('../../utils/logger'),
10 serveStatic = require('serve-static'),
11 readConfig = require('../../utils/readConfig');
12
13var gulpServer = require('./server/gulpfile'),
14 proxyMiddleware = require('../middleware/proxy'),
15 prdToTestMiddleware = require('../middleware/prdToTest'),
16 corsMiddleware = require('../middleware/cors');
17
18var httpsServerInstance = null,
19 httpServerInstance = null;
20
21
22var config = {
23 name: 'dev',
24 explain: 'start dev server.',
25 command: 'eros dev',
26 options: [{
27 keys: ['-h', '--help'],
28 describe: 'read help.'
29 }, {
30 keys: ['-s', '--ssl'],
31 describe: 'import https ssl crt and key.'
32 }]
33}
34
35function helpTitle() {
36 print.title(config)
37}
38
39function helpCommand() {
40 print.command(config)
41}
42
43function listenPort(server, port) {
44 server.on('error', function(e) {
45 if (e.code === 'EADDRINUSE') {
46 logger.fatal('[ERROR]: Port ' + port + ' already occupied, please close the program that occupies the port or use other ports.');
47 }
48 if (e.code === 'EACCES') {
49 logger.fatal('[ERROR]: Insufficient permissions, please use sudo to execute.');
50 }
51 return process.exit(1);
52 });
53 server.on('listening', function(e) {
54 gulpServer.start('dev');
55 });
56 return server.listen(port);
57}
58
59function run() {
60 if (argv.h || argv.help) {
61 helpCommand();
62 } else {
63 var serverConfig = readConfig.get('server') || {},
64 ssl = argv.s || argv.ssl,
65 app = connect();
66 app.use(corsMiddleware)
67 .use(prdToTestMiddleware())
68 .use(proxyMiddleware())
69 .use(serveStatic(path.join(process.cwd(), serverConfig.path || '../')))
70 .use(serveIndex(path.join(process.cwd(), serverConfig.path || '../')));
71 if (ssl) {
72 var opts = {
73 key: fs.readFileSync(path.resolve(process.cwd(), ssl + ".key")),
74 cert: fs.readFileSync(path.resolve(process.cwd(), ssl + ".crt"))
75 };
76 if (httpsServerInstance) {
77 httpsServerInstance.close()
78 httpsServerInstance = null
79 }
80 httpsServerInstance = https.createServer(opts, app)
81 listenPort(httpsServerInstance, serverConfig.port || 443);
82 } else {
83 if (httpServerInstance) {
84 httpServerInstance.close()
85 httpServerInstance = null
86 }
87 httpServerInstance = http.createServer(app)
88 listenPort(httpServerInstance, serverConfig.port || 80);
89 }
90 }
91}
92
93module.exports = {
94 run: run,
95 config: config,
96 helpTitle: helpTitle,
97 helpCommand: helpCommand
98}
\No newline at end of file