-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
82 lines (72 loc) · 1.73 KB
/
index.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
'use strict'
const freePort = require('get-port')
const TempServer = require('./TempServer')
const DEFAULT_HOST = '127.0.0.1'
const DEFAULT_PORT = 8080
/**
* Returns the host.
*
* @param {string} [host] - The host. The default host is "127.0.0.1".
*
* @returns {string} The host.
*/
function getHost (host = DEFAULT_HOST) {
return host
}
/**
* Returns a free port.
*
* @param {number} [port] - The port. If no port given, the default port is 8080.
*
* @returns {number} The free port.
*/
async function getPort (port = DEFAULT_PORT) {
const availablePort = await freePort({ port: port })
return availablePort
}
/**
* Returns the URL. The default URL is "http://127.0.0.1:8080".
*
* @param {string} [host] - The host. The default host is "127.0.0.1".
* @param {number} [port] - The port. If no port given, the default port is 8080.
*
* @returns {string} The URL with the given port.
*/
async function getUrl (host = DEFAULT_HOST, port = DEFAULT_PORT) {
host = getHost(host)
port = await getPort(port)
return `http://${host}:${port}`
}
/**
* Starts a temporary server for testing purposes.
*
* @param {*} [args] - If one argument is specified, that will be the (port).
* If two arguments, they will be the (host, port).
*
* @returns {Promise<TempServer>}
*/
async function startTempServer (...args) {
let host = DEFAULT_HOST
let port = DEFAULT_PORT
if (args.length === 1) {
port = args[0]
} else if (args.length > 1) {
host = args[0]
port = args[1]
}
const server = new TempServer(host, port)
return server.start()
}
/**
* Server module.
*
* @module dev-toolbox/server
*/
module.exports = {
DEFAULT_HOST,
DEFAULT_PORT,
getHost,
getPort,
getUrl,
startTempServer
}