-
Notifications
You must be signed in to change notification settings - Fork 683
/
listening.js
102 lines (82 loc) · 2.08 KB
/
listening.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// Native
const { basename } = require('path')
// Packages
const { write: copy } = require('clipboardy')
const ip = require('ip')
const pathType = require('path-type')
const chalk = require('chalk')
const boxen = require('boxen')
const { coroutine } = require('bluebird')
const opn = require('opn')
module.exports = coroutine(function*(
server,
current,
inUse,
clipboard,
open,
ssl
) {
const details = server.address()
const isTTY = process.stdout.isTTY
const shutdown = () => {
server.close()
// eslint-disable-next-line unicorn/no-process-exit
process.exit(0)
}
process.on('SIGINT', shutdown)
process.on('SIGTERM', shutdown)
let isDir
try {
isDir = yield pathType.dir(current)
} catch (err) {
isDir = false
}
if (!isDir) {
const base = basename(current)
console.error(
chalk.red(`Specified directory ${chalk.bold(`"${base}"`)} doesn't exist!`)
)
// eslint-disable-next-line unicorn/no-process-exit
process.exit(1)
}
if (process.env.NODE_ENV !== 'production') {
let message = chalk.green('Serving!')
if (inUse) {
message +=
' ' +
chalk.red(
`(on port ${inUse.open}, because ${inUse.old} is already in use)`
)
}
message += '\n\n'
const localURL = `http${ssl ? 's' : ''}://localhost:${details.port}`
message += `- ${chalk.bold('Local: ')} ${localURL}`
try {
const ipAddress = ip.address()
const url = `http${ssl ? 's' : ''}://${ipAddress}:${details.port}`
message += `\n- ${chalk.bold('On Your Network: ')} ${url}`
} catch (err) {}
if (isTTY && clipboard) {
try {
yield copy(localURL)
message += `\n\n${chalk.grey('Copied local address to clipboard!')}`
} catch (err) {}
}
if (isTTY && open) {
try {
opn(localURL)
} catch (err) {}
}
if (!isTTY) {
console.log(`serve: Running on port ${details.port}`)
return
}
console.log(
boxen(message, {
padding: 1,
borderColor: 'green',
margin: 1
})
)
}
})