-
Notifications
You must be signed in to change notification settings - Fork 3
/
static-server.js
72 lines (57 loc) · 1.78 KB
/
static-server.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
import http from 'http'
import { loadDependency } from '../utils'
export default class StaticServer {
static async loadDependencies() {
if (StaticServer.serveStatic) {
return
}
StaticServer.serveStatic = await loadDependency('serve-static')
StaticServer.finalhandler = await loadDependency('finalhandler')
}
static load(browser) {
if (!browser.config.staticServer) {
return
}
if (browser.config.staticServer === true) {
const { folder } = browser.config
browser.config.staticServer = { folder }
}
if (!browser.config.staticServer.folder) {
return
}
browser.hook('start:before', () => StaticServer.start(browser.config.staticServer, browser.config.quiet))
browser.hook('close:after', StaticServer.stop)
}
static async start(config, quiet) {
await StaticServer.loadDependencies()
const host = process.env.HOST || config.host || 'localhost'
const port = process.env.PORT || config.port || 3000
const serve = StaticServer.serveStatic(config.folder)
const server = http.createServer((req, res) => {
serve(req, res, StaticServer.finalhandler(req, res))
})
await new Promise((resolve, reject) => {
server.on('error', reject)
server.listen(port, host, () => {
if (!quiet) {
// eslint-disable-next-line no-console
console.info(`tib: Static server started on http://${host}:${port}`)
}
config.host = host
config.port = port
StaticServer.server = server
resolve(server)
})
})
}
static stop() {
if (StaticServer.server) {
return new Promise((resolve) => {
StaticServer.server.close(() => {
StaticServer.server = undefined
resolve()
})
})
}
}
}