Reputation: 73
I am building an application that uses a child process to make mathematical calculations:
var child = exec('get_hrv -M -R rr.txt', function(error, stdout) {
if (error !== null) {
console.log('exec error: ' + error);
} else {
res.send(stdout);
}
});
The output (stdout) looks like this:
NN/RR = 0.992424
AVNN = 789.443
SDNN = 110.386
SDANN = 0
SDNNIDX = 110.386
rMSSD = 73.5775
pNN50 = 36.9231
TOT PWR = 12272.8
ULF PWR = 788.161
VLF PWR = 4603.59
LF PWR = 4221.97
HF PWR = 2659.05
LF/HF = 1.58777
Everything is working as it should, however, this output is a string and I need the values it contains assigned to separate integer variables, e.g. like this:
var extractedVars = {
NN/RR: 0.992424
AVNN: 789.443
SDNN: 110.386
SDANN: 0
SDNNIDX: 110.386
rMSSD: 73.5775
pNN50: 36.9231
TOT PWR: 12272.8
ULF PWR: 788.161
VLF PWR: 4603.59
LF PWR: 4221.97
HF PWR: 2659.05
LF/HF: 1.58777
}
How can this be done? Regex?
Upvotes: 0
Views: 144
Reputation: 13532
You can try something like this
var lines = dataFromProc.split(require('os').EOL);
var data = {};
lines.forEach(function (line) {
var parts = line.split('=');
if (parts[1]) {
data[parts[0].trim()] = parseFloat(parts[1].trim());
}
});
console.log(data);
Upvotes: 1
Reputation: 5733
Since you mentioned regular expressions I wrote a solution using regexp. I'm not sure I would use this solution since the others probably are easier to read, but here it goes anyway. The key goes into capture group 0 and the value into group 1.
var regexp = /([0-9A-Za-z\/ ?]*)= ([0-9\.]*)/;
var extractedVars = {}
data.split(os.EOL).forEach(function (line) {
var res = regexp.exec(line);
extractedVars[res[1].trim()] = parseFloat(res[2]);
});
The expression on regexr
Upvotes: 1