better code: deduplicated code
Massimo Melina committed
Aug 21, 2023 at 10:13 UTC
a0ef6373a8c157ea787c19131e3b35f4c0eb980d
2 files changed
+14
-20
src/listen.ts
+13
-19
@@ -33,7 +33,7 @@ portCfg.sub(async port => {
33
port = await startServer(httpSrv, { port })
34
if (!port) return
35
httpSrv.on('connection', newConnection)
36
- printUrls(port, 'http')
36
+ printUrls(httpSrv.name)
37
if (openBrowserAtStart.get() && !argv.updated)
38
openAdmin()
39
})
@@ -83,7 +83,7 @@ const considerHttps = debounceAsync(async () => {
83
port = await startServer(httpsSrv, { port })
84
if (!port) return
85
httpsSrv.on('connection', newConnection)
86
- printUrls(port, 'https')
86
+ printUrls(httpsSrv.name)
87
})
88
89
@@ -202,9 +202,14 @@ export async function getServerStatus() {
202
const ignore = /^(lo|.*loopback.*|virtualbox.*|.*\(wsl\).*|llw\d|awdl\d|utun\d|anpi\d)$/i // avoid giving too much information
203
204
export function getIps() {
205
- const ips = onlyTruthy(Object.entries(networkInterfaces()).map(([name, nets]) =>
206
- nets && !ignore.test(name) && onlyTruthy(nets.map(net => !net.internal && net.address)) )).flat()
207
- return _.sortBy(ips, x => x.includes(':')) // IPv4 first
205
+ return v4first(onlyTruthy(Object.entries(networkInterfaces()).map(([name, nets]) =>
206
+ nets && !ignore.test(name)
207
+ && v4first(onlyTruthy(nets.map(net => !net.internal && net.address)))[0] // for each interface we consider only 1 address
208
+ )).flat())
209
+
210
+ function v4first(a: string[]) {
211
+ return _.sortBy(a, x => x.includes(':'))
212
+ }
213
}
214
215
export function getUrls() {
@@ -219,18 +224,7 @@ export function getUrls() {
224
})))
225
}
226
222
-function printUrls(port: number, proto: string) {
223
- if (!port) return
224
- for (const [name, nets] of Object.entries(networkInterfaces())) {
225
- if (!nets || ignore.test(name)) continue
226
- _.remove(nets, 'internal')
227
- const first = nets[0]
228
- if (!first) continue
229
- const best = _.find(nets, { family: 'IPv4' }) || first
230
- const appendPort = port === (proto==='https' ? 443 : 80) ? '' : ':' + port
231
- let { address } = best
232
- if (address.includes(':'))
233
- address = '['+address+']'
234
- console.log('network', name, proto + '://' + address + appendPort)
235
- }
227
+function printUrls(srvName: string) {
228
+ for (const url of getUrls()[srvName]!)
229
+ console.log('serving on', url)
230
}
src/update.ts
+1
-1
@@ -2,7 +2,7 @@
2
3
import { getRepoInfo } from './github'
4
import { argv, HFS_REPO, IS_BINARY, IS_WINDOWS, RUNNING_BETA } from './const'
5
-import { basename, dirname, join } from 'path'
5
+import { dirname, join } from 'path'
6
import { spawn, spawnSync } from 'child_process'
7
import { httpsStream, onProcessExit, unzip } from './misc'
8
import { createReadStream, renameSync, unlinkSync } from 'fs'