我想将exec执行的vmstat -s命令的输出转换为对象,以及free -m命令输出
我从exec免费获得-m:
total used free shared buff/cache available
Mem: 7855 2054 1082 257 4718 5243
Swap: 2047 0 2047
对于vmstat -s,我得到此输出
8044160 K total memory
2081200 K used memory
3491012 K active memory
2508932 K inactive memory
1131132 K free memory
579204 K buffer memory
4252624 K swap cache
2097148 K total swap
0 K used swap
2097148 K free swap
328672 non-nice user cpu ticks
3273 nice user cpu ticks
85460 system cpu ticks
4215038 idle cpu ticks
13261 IO-wait cpu ticks
0 IRQ cpu ticks
450 softirq cpu ticks
0 stolen cpu ticks
2095462 pages paged in
3761868 pages paged out
0 pages swapped in
0 pages swapped out
10301935 interrupts
36499667 CPU context switches
1551158702 boot time
17506 forks
那么我怎样才能将此输出转换为
之类的对象objFreeM = {
mem: {total: 7855, used: 2054, ...etc},
swap: {total: 2047, used: 0, free: 2047}
}
objVmstat = {
totalmemory: 8044160,
usedmemory: 2081200,
....etc
}
这是来自vmstat的结果
" 8044160 K total memory\n 2517232 K used memory\n 4064068 K active memory\n 2733260 K inactive memory\n 304940 K free memory\n 650300 K buffer memory\n 4571688 K swap cache\n 2097148 K total swap\n 0 K used swap\n 2097148 K free swap\n 454507 non-nice user cpu ticks\n 3803 nice user cpu ticks\n 117177 system cpu ticks\n 7955496 idle cpu ticks\n 15791 IO-wait cpu ticks\n 0 IRQ cpu ticks\n 528 softirq cpu ticks\n 0 stolen cpu ticks\n 2244129 pages paged in\n 4442696 pages paged out\n 0 pages swapped in\n 0 pages swapped out\n 14232293 interrupts\n 50365325 CPU context switches\n 1551158702 boot time\n 22313 forks\n"
答案 0 :(得分:0)
让我们初始化我们的字符串:
var myString = " 8044160 K total memory\n 2517232 K used memory\n 4064068 K active memory\n 2733260 K inactive memory\n 304940 K free memory\n 650300 K buffer memory\n 4571688 K swap cache\n 2097148 K total swap\n 0 K used swap\n 2097148 K free swap\n 454507 non-nice user cpu ticks\n 3803 nice user cpu ticks\n 117177 system cpu ticks\n 7955496 idle cpu ticks\n 15791 IO-wait cpu ticks\n 0 IRQ cpu ticks\n 528 softirq cpu ticks\n 0 stolen cpu ticks\n 2244129 pages paged in\n 4442696 pages paged out\n 0 pages swapped in\n 0 pages swapped out\n 14232293 interrupts\n 50365325 CPU context switches\n 1551158702 boot time\n 22313 forks\n";
现在我们将其拆分:
var myArray = myString.split("\n");
然后修剪项目:
for (var index in myArray) myArray[index] = myArray[index].trim();
为驼峰式键盘键定义辅助功能:
function camelize(str) {
return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function(letter, index) {
return index == 0 ? letter.toLowerCase() : letter.toUpperCase();
}).replace(/\s+/g, '');
}
最后分析结果:
var results = {};
for (var item of myArray) {
var temp = item.split(" ");
var value = temp[0];
var key = "";
var start = 1;
if (temp[1] === "K") {
value += " K";
start = 2;
} else {
key = "";
}
for (var index = start; index < temp.length; index++) key += " " + temp[index];
key = key.trim();
if (key || value) results[camelize(key)] = value;
}