用流利的ffmpeg捕获错误的正确方法

时间:2016-05-31 07:23:41

标签: node.js fluent-ffmpeg

我在我的NodeJS应用程序中使用Fluent FFMpeg,并且我尝试在输入不存在的情况下添加一些错误处理。目前它只是崩溃了这条消息:

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: ffmpeg exited with code 1: http://localhost:9001: Connection refused

当输入源不存在时,我想等一段时间(比如1秒)再试一次。这是我目前的代码:

var command = FFmpeg("http://localhost:9001")
  // set options here
;

var stream = command.pipe();
stream.on('data', function(chunk) {
  // do something with the data
});

当输入还没有存在时,如何正确地处理错误?

2 个答案:

答案 0 :(得分:1)

要捕获错误,您可以使用try,catch构造函数。以下可能是一种可能的实施方式:

var FFmpeg = require('ffmpeg')

function ffmepgFunction(timeout, attempts) {
    try {
    var command = FFmpeg("http://localhost:9001");

    var stream = command.pipe();
    stream.on('data', function(chunk) {
    // do something with the data
    });
    } catch(e) {
        console.log(e);
        if(attempts > 0)
            setTimeout(() => ffmepgFunction(timeout, --attempts), timeout);
    }
}

ffmepgFunction(2000, 5);

答案 1 :(得分:1)

您可以在“错误”处理程序中获取错误信息,如:

stream.on('error', function(err, stdout, stderr) {
  console.log("ffmpeg stdout:\n" + stdout);
  console.log("ffmpeg stderr:\n" + stderr);
})