我在节点js中使用ffmpeg,想获取输出的字符串:

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


解析为变量,以便以后可以将其查询到mysql数据库中,以便以后在数据表上进行排序和显示。

问题是jsfiddle中的此代码可以按预期工作...但是在节点js中,当我使用多个拆分和修剪函数时出现此错误:

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


这是我尝试从jsfiddle转换的节点js的方法:

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/

更新#2:
使用上面的代码,我得到第一个分割的字符串,我得到这个:

347 fps


那么如何在节点js中删除fps?如果我打电话给另一个:

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


我得到
    TypeError:无法调用未定义的方法“ split”

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

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

最佳答案

因此,如果您的数据字符串如下所示:

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


然后,您可能希望像这样处理它:

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 }


正则表达式说明:

[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

关于javascript - Node JS不能在字符串缓冲区上使用多个分割和 trim 功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41635630/

10-12 12:59
查看更多