-
Notifications
You must be signed in to change notification settings - Fork 0
/
getopt.js
86 lines (66 loc) · 1.99 KB
/
getopt.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
84
/**
* Created by kisstheraik on 16/12/31.
* nodejs 版的 getopt函数
* v1.0
*/
exports.getopt=function(argv,optString,actionList) {
var result={};
for(var i=0;i<argv.length;i++){
var c = argv[i];
//读取参数
if( c == '-' ) {
i++;
c = argv[i];
//查找opt里面字符的位置
var index = optString.indexOf(c);
if (index >= 0) {
var currentC = c;
if (optString[index + 1] == ':') {
if (optString[index + 2] == ':') {
i++;
//两个冒号
while(argv[i] == ' '){
i++;
}
result[currentC]=getPara(argv,i);
} else {
i++;
//一个冒号
if(argv[i]==' '){
actionList[currentC](c);
}else {
while (argv[i] == ' ') {
i++;
}
result[currentC]=getPara(argv,i);
}
}
} else {
//没有冒号
result[currentC]=getPara(argv,i);
}
} else {
//没有相应的短参数
console.log('no para for '+c);
}
}
}
if(actionList!=null) {
for (var key in result) {
//如果回调是一个函数
if(typeof actionList[key] == 'function') {
actionList[key](result[key]);
}
}
}
function getPara(str,index) {
var result='';
for(var i=index;i<str.length;i++){
if(str[i] != ' '){
result+=str[i];
}else break;
}
return result.trim();
}
return result;
};