-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcli.js
executable file
·83 lines (70 loc) · 1.98 KB
/
cli.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
#!/usr/bin/env node
'use strict'
const mri = require('mri')
const path = require('path')
const envPaths = require('env-paths')
const pkg = require('./package.json')
const argv = mri(process.argv.slice(2), {
boolean: [
'help', 'h',
'version', 'v',
'headless'
]
})
const cfgPath = path.join(envPaths(pkg.name, {suffix: ''}).data, 'config.json')
if (argv.help || argv.h) {
process.stdout.write(`
Usage:
fasp-server init <name> <port>
Generate a unique ID, store name and port in a config file at
${cfgPath}.
fasp-server
Run the server with the name port from the config file.
Options:
--headless No window, no video. Also disables --artwork. Default: false
\n`)
process.exit(0)
}
if (argv.version || argv.v) {
process.stdout.write(`fasp-server v${pkg.version}\n`)
process.exit(0)
}
const showError = (err) => {
if (process.env.NODE_DEBUG === pkg.name) console.error(err)
else console.error(err.message || (err + ''))
process.exit(1)
}
const fs = require('fs')
const cmd = argv._[0]
if (cmd === 'init') {
const mkdirp = require('mkdirp')
const {randomBytes} = require('crypto')
const name = argv._[1]
if ('string' !== typeof name || !name) showError('Missing name.')
// todo: use get-port if no port given
const port = parseInt(argv._[2])
if (Number.isNaN(port) || port <= 0) showError('Invalid or missing port.')
const id = randomBytes(8).toString('hex')
mkdirp.sync(path.dirname(cfgPath))
fs.writeFileSync(cfgPath, JSON.stringify({id, name, port}))
console.info('Done.')
} else {
let cfg
try {
cfg = fs.readFileSync(cfgPath, {encoding: 'utf8'})
} catch (err) {
if (err && err.code === 'ENOENT') {
showError('Create a config file with the init command first.')
}
showError(err)
}
const {id, name, port} = JSON.parse(cfg)
const createServer = require('fasp-server')
createServer({
id, name, port,
headless: argv.headless
}, (err) => {
if (err) showError(err)
else console.info(`${name} (${id}) listening on ${port}.`)
})
}