user2631534
user2631534

Reputation: 477

Node JS cannot use multiple split and trim functions on string buffer

I im using ffmpeg in node js and would like to get outputed string:

frame=  986 fps=100 q=-1.0 size=N/A time=00:00:39.40 bitrate=N/A speed=4.01x

to parse into variables so that i can later query it into mysql database for later sorting and showing on datatables.

the problem is that this code in jsfiddle works as expected...but in node js i get this error when i use multiple split and trim functions:

TypeError: Cannot call method 'split' of undefined
TypeError: Cannot call method 'trim' of undefined

Here is what i try on node js converted from jsfiddle:

streams[id].stderr.on('data', function(data) {
    data = data.toString().split('=');
    var frame = data[1].trim().split(' ');
    console.log(frame[0]);
});

JSFIDDLE: https://jsfiddle.net/o32z7yb0/

UPDATE #2: Using above code i get first split string i get this:

347 fps

so how can i remove fps in node js? if i call another:

datas[1].split(' fps');

i get TypeError: Cannot call method 'split' of undefined

streams[id].stderr.on('data', function(data) {
    var datas = data.toString().split('=');

    console.log(datas[1]);
});

Upvotes: 0

Views: 351

Answers (1)

Jared Smith
Jared Smith

Reputation: 21983

So if your data string looks like this:

var str = "frame=  986 fps=100 q=-1.0 size=N/A time=00:00:39.40 bitrate=N/A speed=4.01x";

Then you likely want to process it like so:

let parts = str

  // match will separate it out into an array of pieces
  .match(/[a-zA-Z]+\s*=\s*[a-zA-Z\/0-9\.\-:]+/g)

  // split each piece on the '=' with optional surrounding whitespace.
  .map(str => str.split(/\s*=\s*/)

  // put the name/value pairs into an object
  .reduce((acc, arr) => {
    let prop = arr[0];
    let val = arr[1];
    acc[prop] = val;
    return acc;
  }, {});

console.log(parts); // { "frame": "896", "fps": "100", ...etc }

Regex explanation:

[a-zA-Z]+ // match any letter one or more times
\s*       // match any whitespace char zero or more times
=         // match =
\s*       // same as above
[
  a-zA-Z  // match any letter
  0-9     // any number
  \/\.\-: // . : / any of those three
]+        // ... one or more times
g flag    // get all matches

Upvotes: 1

Related Questions