Differentiate between error and standard terminal log with ffmpeg - nodejs

前端 未结 2 2138
一生所求
一生所求 2021-02-13 17:58

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 su

2条回答
  •  半阙折子戏
    2021-02-13 18:32

    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');
    ...
    

提交回复
热议问题