0

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?

2
  • Is the code that produces the output yours? Commented Mar 9, 2015 at 21:51
  • No, I am using a shell script from Physionet HRV Toolkit (physionet.org/tutorials/hrv-toolkit). Commented Mar 9, 2015 at 21:59

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

This assumes line feeds are CRLF ("\r\n"). Assuming get_hrv uses the platform's EOL character, require('os').EOL will be more true. See stackoverflow.com/a/14063413/1481489
1

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

2 Comments

is there a difference between your solution and the others in terms of performance?
Looks like the regex one is a little bit faster on chrome at least jsperf.com/regexp-vs-split-so , although it's probably not worth the harder to read code IMO.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.