1 | const tcpPortUsed = require('tcp-port-used')
|
2 | const createServer = require('./createServer')
|
3 | const PORT = require('../util/PORT')
|
4 | const setConf = require('../conf/set')
|
5 | const IP = require('../util/IP')
|
6 | const HOSTS = require('../util/HOSTS')
|
7 | const root = process.cwd()
|
8 | const conf = require('../conf/conf')()
|
9 | const os = require('os')
|
10 | const H = {
|
11 | http: require('http'),
|
12 | https: require('https')
|
13 | }
|
14 | const { spawn } = require('child_process')
|
15 |
|
16 | const explorer = (port = 80, host = IP) => {
|
17 | const withStart = process.argv.includes('start')
|
18 | const protocal = port === 443 ? 'https' : 'http'
|
19 | const url = protocal + '://' + host + ':' + port
|
20 | console.log('waiting for start ...')
|
21 | H.http.get(url, function (res) {
|
22 | console.log('server starting on: ' + url)
|
23 | withStart && spawn(os.type().match(/Windows/) ? 'explorer' : 'open', [ url ])
|
24 | }).on('error', function (err) {
|
25 | console.log(err)
|
26 | })
|
27 | }
|
28 | module.exports = ({
|
29 | port = conf.port,
|
30 | host = conf.host
|
31 | }) => {
|
32 | if (host) {
|
33 | port = port || 80
|
34 | HOSTS(host)
|
35 | }
|
36 | if (port) {
|
37 | port = port | 0
|
38 | }
|
39 |
|
40 | if (port) {
|
41 | setConf({port, host, root})
|
42 | tcpPortUsed
|
43 | .check(port, IP)
|
44 | .then(inUse => {
|
45 | inUse || conf.onServerCreate(createServer(port))
|
46 | explorer(port, host)
|
47 | }).catch(err => console.error(err))
|
48 | } else {
|
49 | PORT().then(port => {
|
50 | setConf({port, host, root})
|
51 | conf.onServerCreate(createServer(port))
|
52 | explorer(port, host)
|
53 | }).catch(err => console.error(err))
|
54 | }
|
55 | }
|