UNPKG

1.62 kBJavaScriptView Raw
1const tcpPortUsed = require('tcp-port-used')
2const createServer = require('./createServer')
3const PORT = require('../util/PORT')
4const setConf = require('../conf/set')
5const IP = require('../util/IP')
6const HOSTS = require('../util/HOSTS')
7const root = process.cwd()
8const conf = require('../conf/conf')()
9const os = require('os')
10const H = {
11 http: require('http'),
12 https: require('https')
13}
14const { spawn } = require('child_process')
15
16const 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}
28module.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}