-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
118 lines (100 loc) · 2.48 KB
/
Copy pathindex.js
File metadata and controls
118 lines (100 loc) · 2.48 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#!/usr/bin/env node
const program = require('commander')
const fs = require('fs')
const path = require('path')
var config = require('./config.json')
program.version('2.0.0')
// commands
program
.command('start')
.description('Start the proxy server')
.action(function () {
require('./app')
})
program
.command('ls')
.description('List all the configs')
.action(ls)
program
.command('add <hostname> <port>')
.description('Add a config')
.action(add)
program
.command('set <hostname> <port>')
.description('Set an existed config')
.action(set)
program
.command('del <hostname>')
.description('Delete an existed config')
.action(del)
program.parse(process.argv)
if (process.argv.length === 2) {
program.outputHelp()
}
// actions
function ls () {
var output = '\n\r'
Object.keys(config).forEach(function (hostname) {
var port = config[hostname]
output += line(hostname) + port + '\n\r'
})
console.log(output === '\n\r' ? 'no config found' : output)
}
function add (hostname, port) {
var isExist = new Set(Object.keys(config)).has(hostname)
if (isExist) {
return error('hostname %s already exists', hostname)
}
var isNaN = Number.isNaN(+port)
if (isNaN) {
return error('port %s should be a number', port)
}
config[hostname] = +port
save(config)
}
function set (hostname, port) {
var isNotExist = !new Set(Object.keys(config)).has(hostname)
if (isNotExist) {
return error('hostname %s not exists', hostname)
}
var isNaN = Number.isNaN(+port)
if (isNaN) {
return error('port %s should be a number', port)
}
var is80 = +port === 80
if (is80) {
return error('port should not be 80')
}
config[hostname] = +port
save(config)
}
function del (hostname) {
var isNotExist = !new Set(Object.keys(config)).has(hostname)
if (isNotExist) {
return error('hostname %s not exists', hostname)
}
delete config[hostname]
save(config)
}
// helpers
function line (str) {
str = String(str)
return (
str + ' ' + Array(20 - str.length > 0 ? 20 - str.length : 1).join('-') + ' '
)
}
function error () {
arguments[0] = '\n\r An error occured: ' + arguments[0]
Array.prototype.push.call(arguments, '\n\r')
console.log.apply(null, arguments)
}
function save (config) {
var isNotObj = typeof config !== 'object'
if (isNotObj) {
return error('variable config should be a json object')
}
return fs.writeFileSync(
path.resolve(__dirname, './config.json'),
JSON.stringify(config, null, 2)
)
}