Differentiate between error and standard terminal log with ffmpeg - nodejs

|▌冷眼眸甩不掉的悲伤 提交于 2020-02-21 10:27:34

问题


I'm using ffmpeg in node js. Both the standard terminal output and the error seems to be sent to stdout, so I don't know how to differentiate between error and success... Here's my code:

var convertToMp3 = function(filePath) {
  var ffmpeg = child_process.spawn('ffmpeg',['-i', filePath, '-y', 'output.mp3']);
  var err = '';
  ffmpeg.stderr
    .on('data', function(c) { err += c; })
    .on('end', function() { console.log('stderr:', err); });
  var d = '';
  ffmpeg.stdout
    .on('data', function(c){d +=c;})
    .on('end', function(){ console.log('stdout', d); });
}

wether the conversion succeeds or fails, stdout is empty and stderr contains what I'd get if I'd run the corresponding command in the terminal


回答1:


Ffmpeg outputs all of its logging data to stderr, to leave stdout free for piping the output data to some other program or another ffmpeg instance.

When running ffmpeg as an automatic process it's often useful give the option

-loglevel error

which turns it completely mute in a normal scenario and only outputs the error data (to stderr), which is normally what you would expect from a command-line program.




回答2:


Inspired by @aergistal comment, here is a solution that works for me, where callback is to be executed at the end of the task, with the signature function(error, success), as usual.

var convertToMp3 = function(filePath, callback) {
  var ffmpeg = child_process.spawn('ffmpeg',['-i', filePath, '-y', 'output.mp3']);
  var err = '';
  ffmpeg.stderr.on('data', function(c) { err += c; }).on('end', function() { console.log('stderr:', err); });

  ffmpeg.on('exit', function(code) {
    if (code) {
      callback({code: code, message: err});
    } else {
      callback(null, {success: true, message: err});
    }
  });
}

or in the new js style:

const convertToMp3 = (filePath) => new Promise((resolve, reject) {
  const ffmpeg = child_process.spawn('ffmpeg', ['-i', filePath, '-y', 'output.mp3']);
  let output = '';
  ffmpeg.stderr
    .on('data', c => { output += c; });

  ffmpeg.on('exit', code => {
    if (code) {
      reject({ code: code, message: output });
    } else {
      resolve(output);
    }
  });
});

const ffmpegOutput = await convertToMp3('./video.mp4');
...


来源:https://stackoverflow.com/questions/35169650/differentiate-between-error-and-standard-terminal-log-with-ffmpeg-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!